Docker Cheat Sheet
Quick reference from FreeCodingCourses.com
Images
docker pull node:20- download an image from a registry.
docker build -t myapp .- build an image from the Dockerfile here, tag it myapp.
docker images- list local images.
docker rmi myapp- remove an image.
Run containers
docker run myapp- start a container from an image.
docker run -p 3000:3000 myapp- map host port 3000 to container port 3000.
docker run -d myapp- detached: run in the background.
docker run -it ubuntu bash- interactive shell inside the container.
docker run --env-file .env myapp- pass environment variables.
Manage containers
docker ps- running containers. docker ps -a includes stopped.
docker logs -f <id>- view and follow a container's output.
docker exec -it <id> bash- open a shell in a running container.
docker stop <id> docker start <id>- stop and restart.
docker rm <id>- delete a stopped container.
A basic Dockerfile
FROM node:20- start from a base image.
WORKDIR /app- set the working directory inside the image.
COPY package*.json ./ RUN npm ci- copy deps first, install, so this layer caches.
COPY . .- copy the rest of your code.
CMD ["node", "server.js"]- the command that runs when the container starts.
docker compose (multi-container)
docker compose up -d- start everything in compose.yaml, detached.
docker compose down- stop and remove the containers.
docker compose logs -f- tail logs from all services.
docker compose ps- status of the compose services.
Clean up
docker system prune- remove stopped containers, unused networks, dangling images.
docker image prune -a- remove all unused images. Frees a lot of disk.
docker volume ls- list volumes (your persistent data lives here).
Gotchas worth knowing
- •Copy package.json and install dependencies before copying the rest of your code. Docker caches layers, so your slow install step is reused whenever only your source changed.
- •Containers are disposable and lose their internal changes when removed. Anything that must survive, like a database, belongs in a named volume.
- •docker system prune reclaims disk from stopped containers and dangling images. Run it when Docker starts eating your drive, but know it deletes stopped containers.
- •-p host:container maps ports. If you cannot reach your app in the browser, you probably forgot the -p flag or mapped the wrong port.