Building a Docker image means assembling application files, runtime dependencies and startup instructions into an immutable image artifact. The most important decisions are not the syntax of docker build alone: the source context, base image, dependency pinning, runtime permissions and validation steps determine whether an image is reproducible and safe to deploy. This tutorial shows a deliberately small Python HTTP service so the commands are understandable without a larger framework.
Understand the three ingredients
A Dockerfile describes how to build the image. The build context supplies local files that instructions such as COPY can access. The resulting image contains layers and metadata; a container is a running instance created from that image. An image is not a virtual machine, and a successful image build does not guarantee that the application starts or stays healthy.
Create a working directory with the files shown below. Avoid building from your home directory: an unnecessarily large context can accidentally include secrets, archives or source files unrelated to the application.
Create a minimal application
Put the following illustrative program in app.py. It serves a plain response on port 8080 so you can test that the container starts and accepts a request.
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "text/plain; charset=utf-8")
self.end_headers()
self.wfile.write(b"Hello from a container!\n")
if __name__ == "__main__":
HTTPServer(("0.0.0.0", 8080), Handler).serve_forever()
This built-in server is a teaching example, not a production-grade web server. For a real application, choose a supported server, set timeouts and limits, and implement appropriate health and shutdown behavior.
Write a small Dockerfile
Save the following as Dockerfile in the same directory. The Python tag is illustrative; choose a currently supported version and pin a reviewed image digest in production pipelines. A numeric nonroot user reduces some unnecessary container privileges.
FROM python:3.13-slim
WORKDIR /app
COPY app.py /app/app.py
USER 10001:10001
EXPOSE 8080
CMD ["python", "app.py"]
EXPOSE documents a container port; it does not publish that port to the host. The CMD instruction defines the default process. If the application needs to create files, design ownership and writable paths explicitly rather than reverting to root.
Keep unwanted files out of the build context
Create a .dockerignore file so the build client does not send local secrets, caches and large unrelated directories into the context:
.git/
.venv/
__pycache__/
*.pyc
.env
.env.*
node_modules/
build/
dist/
Adjust exclusions to the actual project. Docker’s ignore semantics resemble, but are not identical to, Git ignore rules. Do not rely on .dockerignore as the only secret protection: build arguments, package manager logs and copied files can still expose sensitive data if the Dockerfile is careless.
Build the image and test the result
From the directory containing the files, build the image with a meaningful local tag:
docker build --pull -t hello-http:lab-1 .
docker image inspect hello-http:lab-1
Here the final . is the build context. The --pull option checks for newer versions of referenced base images; it does not make dependency versions immutable. Record the resulting image digest and source revision if the artifact will be promoted between environments.
Run the container bound to the host loopback interface so the demonstration server is not exposed on every network interface:
docker run --rm -p 127.0.0.1:8080:8080 hello-http:lab-1
# In another terminal:
curl -i http://127.0.0.1:8080/
You should see an HTTP response with the message from the program. If the container exits, inspect logs and the container process; do not assume a built image contains all runtime requirements.
How Docker image layers affect builds
Docker builds can reuse cached layers when inputs have not changed. For applications with dependencies, a common pattern is to copy the dependency manifest first, install dependencies with pinned versions, and then copy the source code so ordinary code edits do not invalidate every earlier build step. Use a multi-stage build when it helps keep compilers or build tools out of the final runtime image.
Base image updates, package registry availability and the chosen target architecture can still change output across rebuilds. An image tag is a convenient name, but pinning by digest and recording a software bill of materials are stronger reproducibility practices.
Apply practical security controls
Use the smallest maintained base that supports your application, run nonroot when feasible, patch and rebuild regularly, and scan dependencies and the resulting image. Never embed API keys, passwords or private SSH material in Dockerfile instructions or image layers. Use an approved runtime secrets mechanism and restrict network and filesystem permissions.
Distinguish build-time from runtime configuration. Environment variables may be appropriate for nonsecret settings, but sensitive values need a secure store and careful access control. Do not grant privileged containers or mount the Docker socket merely to make a development example work.
Build automation and deployment acceptance
In CI, tie the image to a source commit, test the application, scan the image, sign or attest the artifact where supported, and deploy the same digest that was tested. Implement health checks, resource limits and rollback behavior appropriate to the target platform. Check the resulting running application rather than treating docker build exit code zero as production acceptance.
The official Docker build context documentation explains how files enter builds, and the Dockerfile best practices cover base images, cache, and security. Use those references when moving beyond this lab and creating production images.
Investigate common image-build failures
If COPY cannot find a file, confirm that you are running docker build from the intended context and that the file was not excluded by .dockerignore. If package installation fails, check the base image’s package manager, network access, proxy configuration and exact dependency versions. If the image builds but the container exits, inspect application logs and the container’s exit status before changing build flags.
Port-publishing mistakes are also common: EXPOSE 8080 does not publish host port 8080, and a server bound to 127.0.0.1 inside the container may not be reachable through a published port. In this tutorial, the Python server binds to 0.0.0.0 inside the container while the host publication is restricted to 127.0.0.1. These are different network boundaries.
Rebuild versus redeploy
An image is a versioned artifact. Building a new image does not update containers that are already running the old image, and restarting an old container does not automatically replace its image. Deploy the newly verified digest explicitly through the target orchestration platform. Keep the prior digest available so you can roll back after a failed release.
For a multi-service system, pay attention to database migration compatibility, health checks and dependency order. Infrastructure, application configuration and persistent data may require separate rollback plans. Container isolation does not remove operational responsibility for network permissions, system updates and backup recovery.