Docker Basics and the Dockerfile
Docker Basics and the Dockerfile
Packaging with Docker
Docker is the tool that made containers practical. A developer builds a container image containing their application and its runtime, and that same image runs anywhere Docker does - on a laptop, a server, or in a cluster. No more it-works-on-my-machine.
Two key terms: an image is a read-only template, and a container is a running instance of an image. One image can launch many containers.
Your First Dockerfile
A Dockerfile is a text file with the build instructions. The FROM line picks a base image, WORKDIR sets the working directory, COPY adds files, and CMD declares what runs when the container starts.
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Each instruction creates a layer. Docker caches layers, so lines that rarely change, such as installing dependencies, should come before lines that change often, such as copying source code. Reordering them changes rebuild speed significantly.
Building and Running
Build an image from the Dockerfile and run a container from it:
docker build -t myapp .
docker run -p 8000:8000 myapp
The -p flag maps a host port to a container port. The container talks on port 8000 internally, and localhost:8000 on your machine now reaches it.
Handy Daily Commands
docker ps # running containers
docker images # local images
docker logs <name> # container output
docker stop <name> # stop a container
Why Images Behave the Same
The image bundles the runtime: the base OS libraries, Python, and your code. The same image run in development, testing, and production uses identical versions of everything, which is the core promise of containerization and the reason teams trust containers for deployments.
Key Points
- An image is a read-only template; a container is a running instance.
- The Dockerfile defines the image: base, workdir, copy, run, and command.
- Order layers so rarely changed steps come first to reuse the cache.
- docker build creates an image; docker run launches a container.
- Ports are mapped with -p host:container.