Skip to content
IT Vizag
← Production Python

▶ Sign up free for the video, slides & prompts

The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.

Checking…

Docker for Python apps

Lesson 8 of 10 · 2 min read

Package your app so it runs the same everywhere.

🎬 Video version coming soon — read it now

"It works on my laptop" is the oldest problem in software. Docker packages your app with its exact Python version, libraries and settings into an image that runs the same everywhere: a teammate's laptop, a test server or the cloud.

Key words

  • Image: a packaged, read-only snapshot of your app and everything it needs
  • Container: a running instance of an image
  • Dockerfile: the recipe that builds the image

A Dockerfile for the FastAPI app

🔒 Code example: sign up free (above) to unlock it.

Line by line:

  • FROM: start from an official slim Python image
  • ENV: don't write .pyc files, and show logs immediately
  • COPY requirements.txt, then RUN pip install: done before copying the code, so Docker caches the slow install step. Editing your code doesn't reinstall every library
  • COPY . .: add your code
  • USER appuser: don't run as root, which is a basic security practice
  • CMD: the command that starts the app, listening on all interfaces inside the container

.dockerignore

Keep junk and secrets out of the image:

🔒 Code example: sign up free (above) to unlock it.

Build and run

🔒 Code example: sign up free (above) to unlock it.
  • -t names (tags) the image
  • -p 8000:8000 connects port 8000 on your laptop to the container
  • --env-file .env passes secrets in at run time. They're never baked into the image

Open http://localhost:8000/docs and it works exactly as before, now in a container.

Useful commands

🔒 Code example: sign up free (above) to unlock it.

Never put secrets in the image

Anyone who gets the image can read every file in it. Pass secrets as environment variables when the container starts, or through the hosting platform's secrets settings.

Tip: Docker Desktop is free for personal use and education. If your laptop struggles, many hosting platforms build the Dockerfile for you in the cloud, which is the next lesson.

In one line

A Dockerfile packages your app and its dependencies into an image that runs identically everywhere; install dependencies before copying code, run as a non-root user, and pass secrets at run time.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend