A Dockerfile describes how to package application code and dependencies into an image. Using a minimal Flask app, this guide shows which files are available during the build, when Docker can reuse cached layers, and how to verify that the resulting container serves HTTP requests.
Common commands at a glance#
| Command | What it does |
|---|---|
docker build -t flask-hello:1.0 . | Build the image using the current directory |
docker run -p | Run a container and publish a port. See the full example below |
curl http://127.0.0.1:8000 | Check that Flask returns an HTTP response |
docker ps -a --filter name=flask-hello | Check whether the exercise container exited |
docker logs flask-hello | Read the Flask container logs |
docker exec flask-hello ls /app | List the application files in the running container |
docker stop flask-hello | Stop the exercise container if it is still running |
docker rm flask-hello | Remove the stopped exercise container |
Prepare the Application and Build Directory#
Create a clean directory to hold your application code and Dockerfile. This directory becomes the “build context” for the docker build command—Docker packages the files in this directory and sends them to the builder, so COPY instructions in the Dockerfile can access them.
mkdir flask-demo && cd flask-demoapp.py: A Flask application that returns JSON
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/')
def index():
return jsonify({"message": "Flask in Docker", "status": "running"})Gunicorn will load app from app.py and listen on port 8000 inside the container. The Dockerfile below defines how it starts.
requirements.txt: Pin dependency versions
Flask==3.1.3
Werkzeug==3.1.9
gunicorn==27.0.1Pinning versions prevents pulling incompatible newer releases on the next build. These versions were verified as of 2026-11-19; update them based on actual needs later.
.dockerignore: Exclude files that should not enter the build context
.git/
.venv/
__pycache__/
*.pyc
.env
*.log.dockerignore works like .gitignore, but targets the build context. If your directory contains large folders like .git or .venv, failing to exclude them sends everything to the builder, slowing down the build. More importantly, files like .env may contain credentials and should never enter the image.
Understanding the Dockerfile Line by Line#
Dockerfile: This multi-stage build separates dependency installation from the final runtime image. python-base gives both later stages the same Python runtime; builder installs dependencies in a virtual environment, and runtime copies only that environment and the application files.
FROM python:3.11-slim AS python-base
FROM python-base AS builder
WORKDIR /build
COPY requirements.txt .
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install --no-cache-dir -r requirements.txt
FROM python-base AS runtime
WORKDIR /app
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY app.py .
RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
USER appuser
EXPOSE 8000
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app:app"]FROM … AS python-base / builder / runtime
FROM starts a build stage, and AS names it. Both later stages start from python-base, so they use the same Python runtime. The builder stage creates /opt/venv and installs dependencies; the runtime stage takes that directory with COPY --from=builder. python:3.11-slim is a floating tag that may point to a new patch image over time; use a digest when you need to pin the exact content.
**WORKDIR /buildandWORKDIR /app** WORKDIRsets the working directory for the current build stage. The builder stage uses/build, so requirements.txtis copied to/build/requirements.txtand dependencies are installed there. The runtime stage uses/app`, which is also the container’s default working directory at startup.
COPY requirements.txt . / RUN python -m venv / RUN pip install
In the builder stage, copy the dependency list, create a virtual environment, and install the packages. If only app.py changes, Docker can reuse the cached dependency-installation steps.
COPY –from=builder /opt/venv /opt/venv Copy the installed Python virtual environment from the builder stage. Other temporary files in the builder do not enter the final image automatically; only explicitly copied files reach the runtime stage.
COPY app.py . Copy the application code in the runtime stage. Because dependency installation and application files are separate, code changes can reuse the builder’s dependency cache.
RUN useradd … && chown … and USER appuser
Running the application as a non-root user is a basic security practice. This creates the appuser user, transfers ownership of /app to it, then uses the USER instruction to switch. The process started by CMD runs as appuser.
EXPOSE 8000
Declare that the container listens on port 8000. This is image metadata; it does not actually open the port or publish it to the host. Port publishing requires docker run -p.
CMD [“gunicorn”, “–bind”, “0.0.0.0:8000”, “app:app”]
The default command when the container starts. Gunicorn loads the app object from app.py and listens on 0.0.0.0:8000. CMD uses a JSON array (exec form) to avoid shell parsing quirks. Gunicorn starts one worker by default; for production, test worker/thread settings against the workload and available CPU and memory instead of copying a fixed value.
Difference between RUN and CMD: RUN executes during image build, and results are saved in image layers; CMD is the default command when a container starts, not executed during build.
Difference between EXPOSE and -p: EXPOSE is documentation telling users which port the container listens on; docker run -p actually maps the container port to the host, allowing external access.
Build the Image and Understand Caching#
flowchart TD
accTitle: From Flask source files to a running service
accDescr: Docker builds an image from the Dockerfile and build context. At runtime, -p publishes the container port on the host for clients to use.
context["Dockerfile and build context"] -->|docker build| image["Image flask-hello:1.0"]
image -->|docker run| container["Flask container · 8000"]
client["Client on the host"] --> port["127.0.0.1:8000"]
port -->|"-p 127.0.0.1:8000:8000"| containerIn the flask-demo directory, run:
docker build -t flask-hello:1.0 .-t flask-hello:1.0 tags the image, and the trailing . indicates the build context is the current directory. Docker sends files in this directory (except those excluded by .dockerignore) to the builder, then builds layer by layer following the Dockerfile.
The first build pulls the base image and installs dependencies, which takes time. If you build again with the same requirements.txt, Docker reuses the cached COPY requirements.txt and RUN pip install layers, only re-executing later changed layers.
Common reasons cache breaks:
- The contents or relevant file attributes of files used by
COPYchanged; a file’s modification time alone does not invalidate the cache docker build --pullfetched an updated base image- An earlier layer invalidated, forcing all subsequent layers to rebuild
This is why less frequently changing operations (like installing dependencies) go first, and frequently changing ones (like application code) go later. A timestamp change alone does not invalidate the cache; check the file contents and other inputs Docker uses for cache validation.
Image Layers, the Container Writable Layer, and Build Cache#
Think of an image as a stack of read-only filesystem layers. The base image provides the lower layers. Instructions that change the filesystem, such as RUN, COPY, and ADD, usually create new filesystem layers; later layers can replace files from earlier layers in the merged view. Not every Dockerfile instruction adds a filesystem layer: CMD, ENV, EXPOSE, and USER primarily record image configuration or metadata.
When Docker starts a container, it adds a writable container layer on top of the image’s read-only layers. Files created or changed by processes in the container filesystem usually go into this layer; removing the container also removes that layer. Use a volume or bind mount for data that must survive container replacement. A mount over a directory hides the directory’s existing image contents, and volumes and bind mounts have lifecycles distinct from the container writable layer.
Inspect the image build history and the sizes reported for its entries with:
docker history flask-hello:1.0The output helps locate build steps, but its entries do not necessarily correspond one-to-one with Dockerfile lines. Layers and cache let Docker reuse identical build results. However, deleting a large file or secret in a later layer does not erase it from an earlier layer and may not reduce the image size. Keep file creation and cleanup in the same RUN instruction, exclude irrelevant files with .dockerignore, and never put credentials in the build context or image. Multi-stage builds let the final image include only runtime files explicitly copied from earlier stages; they still use image layers and do not flatten them or automatically solve every size or security issue.
What Multi-Stage Builds Solve#
Multi-stage builds let you leave compilers, build tools, and intermediate artifacts in a builder stage while copying only runtime files into the final stage. They are often more valuable when compiling native dependencies or building frontend assets. This Flask example mainly uses Python packages and installs no extra compiler, so the stages demonstrate separation but do not guarantee a smaller image. A single-stage Dockerfile is simpler and reasonable for a small exercise like this. If the builder installs native libraries, the runtime still needs the required shared libraries, and the Python/system ABIs between stages must be compatible.
About build commands: The current CLI keeps docker build as a compatibility entry point for docker buildx build; it defaults to the builder bundled with Docker Engine. Direct use of docker buildx build follows the builder currently selected by Buildx. docker image build is still supported by the CLI, but its reference page documents the legacy builder; that does not mean docker build uses that old backend. This guide uses the common docker build command.
Run and Verify the Flask Service#
After building the image, start a container:
docker run -d --name flask-hello -p 127.0.0.1:8000:8000 flask-hello:1.0-d runs the container in the background, --name gives it a name, and -p 127.0.0.1:8000:8000 publishes container port 8000 on the host’s loopback address. The exercise keeps the container after it exits so you can read logs if startup fails.
Access the service:
curl http://127.0.0.1:8000You should see:
{"message":"Flask in Docker","status":"running"}If the request cannot connect, check the container’s status and then read its logs.
docker ps -a --filter name=flask-hello
docker logs flask-helloFind the row with flask-hello in the NAMES column. If the status is Exited, look for a startup error in the logs. On a successful startup, Gunicorn reports that it is listening on 0.0.0.0:8000. Gunicorn disables access logging by default.
Run a command in the running container#
If the container is still running, use docker exec to inspect the application files.
docker exec flask-hello ls /appThe command to run comes after the container name. Here ls /app should list app.py. requirements.txt is used to install dependencies in the builder stage and is not copied into the runtime image; the installed Python packages are in /opt/venv. If the container has already exited, use docker logs flask-hello to read its earlier output.
Remove the exercise container#
Confirm that flask-hello is the container you created for this exercise. If it is still running, stop it first.
docker stop flask-helloOnce the container stops or exits on its own, remove it.
docker rm flask-helloUse docker images flask-hello to confirm that the image is still available.
Flask documents its bundled server as a development tool. This container uses Gunicorn as the WSGI server that receives HTTP requests and calls the Flask application.
Common Build and Access Issues#
Build error “COPY failed” or file not found
Check the build context path and .dockerignore. The last argument of docker build is the context directory; COPY paths in the Dockerfile are relative to this directory, not the Dockerfile location. If .dockerignore accidentally excludes needed files, COPY fails.
Dependency installation fails or version conflicts
Pin version numbers in requirements.txt and ensure Python version compatibility with dependencies. If the base image Python version differs from your local development environment, dependency issues may arise.
Container starts but is inaccessible
First check if the application really listens on 0.0.0.0 inside the container. If it only binds 127.0.0.1, -p mapping won’t help. Use docker logs to see if Gunicorn reports errors.
Host port already in use
-p 127.0.0.1:8000:8000 requires host port 8000 to be free. If already occupied, use a different port like -p 127.0.0.1:8080:8000, then access http://127.0.0.1:8080.
Gunicorn can’t find application module
app:app in CMD means “import the app object from app.py.” If the filename or object name differs, adjust accordingly. For example, if the file is main.py and the object is application, write main:application.
Older Practices and When They Apply#
Reading older tutorials or notes, you may encounter these patterns:
- Using a CentOS 7 base image: CentOS Linux 7 reached end of life in June 2024. For new projects, choose a base image that still receives security updates.
- MAINTAINER instruction: Deprecated; now use
LABEL maintainer="..."instead. - Using ADD for plain files:
ADDhas extra features like auto-extracting tars and supporting URLs; for plain local file copies,COPYis clearer.ADDisn’t wrong, but unless you need those features,COPYis the clearer choice. - Using flask run in containers: Acceptable for development, but switch to a WSGI server for production deployment.