Docker Basics: Build, Run, and Manage Containers
The core Docker commands for building images, running containers, and managing them in development and production.
Containers changed how I deploy applications. Same environment locally as in production. No "works on my machine" problems. Here's the essential workflow.
Verify Installation
docker --version
Docker version 24.0.5, build ced0996
Write a Dockerfile
A Dockerfile defines how to build your image:
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "app.py"]
This creates a Python environment, installs dependencies, copies your code, and defines the startup command.
Build the Image
docker build -t my-app .
The -t tags the image with a name. The . is the build context (current directory).
Run a Container
docker run -p 8000:8000 my-app
Maps port 8000 on your host to port 8000 in the container.
Run in background:
docker run -d -p 8000:8000 my-app
The -d flag runs detached.
Managing Containers
List running containers:
docker ps
List all containers (including stopped):
docker ps -a
Stop a container:
docker stop <container_id>
Remove a container:
docker rm <container_id>
View logs:
docker logs <container_id>
docker logs -f <container_id> # Follow logs
Execute command in running container:
docker exec -it <container_id> bash
Managing Images
List images:
docker images
Remove image:
docker rmi <image_id>
Clean up unused resources:
docker system prune
Environment Variables
Pass environment variables at runtime:
docker run -e DATABASE_URL=postgres://... my-app
Or use an env file:
docker run --env-file .env my-app
Volumes for Persistent Data
Mount a local directory:
docker run -v $(pwd)/data:/app/data my-app
Changes in /app/data persist on your host.
Key Takeaways
- Dockerfile defines reproducible build instructions
docker build -t name .creates an imagedocker run -p host:container imageruns a container with port mapping- Use
-dfor background execution docker exec -it container bashgets you a shell- Volumes persist data outside the container lifecycle
docker system prunecleans up unused resources
Written by Bar Tsveker
Senior CloudOps Engineer specializing in AWS, Terraform, and infrastructure automation.
Thanks for reading! Have questions or feedback?