Skip to content

Docker Basics

Docker solved “works on my machine” by shipping your machine. It’s a good idea. People still find ways to make it hurt, and I’ve watched most of them happen.

  • Image: a read-only template. Built once, run many times. nginx:1.27, postgres:17.
  • Container: a running (or stopped) instance of an image, plus a thin writable layer on top.

The writable layer dies with the container. Anything you want to keep goes in a volume. See Storage. I’ll keep repeating this until people stop losing databases.

Terminal window
docker ps # running containers
docker ps -a # including the dead ones
docker logs -f --tail 100 web # follow logs
docker exec -it web sh # get a shell inside (bash if the image has it; many don't)
docker inspect web # everything about it, as a wall of JSON
docker stats # live CPU/RAM per container
docker images
docker pull nginx:1.27
docker rm -f web # stop and remove

Running one by hand:

Terminal window
docker run -d --name web \
--restart unless-stopped \
-p 127.0.0.1:8080:80 \
-v /srv/web:/usr/share/nginx/html:ro \
nginx:1.27

If you’re writing a docker run with more than three flags, stop. Write a Compose file. Shell history isn’t documentation.

nginx:latest means “whatever was newest when this host last pulled.” That’s a different thing on every server and a different thing next week. Pin a version: postgres:17, nginx:1.27. For the truly paranoid (correct), pin the digest: nginx@sha256:....

FROM python:3.13-slim
# Deps first, so this layer is cached until requirements change
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
# Don't run as root
RUN useradd --system --uid 10001 app
USER app
EXPOSE 8000
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]

Notes from the trenches:

  • Order layers from least to most frequently changing. Copy the dependency manifest, install, then copy source. Otherwise every code change reinstalls every dependency, and your CI bill notices.
  • Add a .dockerignore. Include .git, node_modules, .env. Especially .env. I’ve pulled secrets out of public images. Don’t make it easy.
  • Use exec form (CMD ["a", "b"]), not shell form (CMD a b). Shell form runs under /bin/sh, which doesn’t forward SIGTERM, so docker stop waits 10 seconds and then kills your app mid-write.
  • Bind to 0.0.0.0 inside the container. An app listening on 127.0.0.1 inside a container can’t be reached from outside it. Every time. Every single time someone asks.
Policy Behavior
no Default. Dies and stays dead.
on-failure Restarts on non-zero exit.
always Restarts always, including after you manually stopped it, once the daemon restarts.
unless-stopped Like always, but respects you stopping it. Use this one.

Make sure the daemon itself starts at boot: sudo systemctl enable --now docker. A restart policy can’t help if Docker never starts.