Docker Cheat Sheet: Images, Containers, Dockerfile and Compose
· Editorial team · 2 min read
cheatsheetdockercontainersdevops
Containers
| Command | Purpose | |---|---| | `docker run -d --name web -p 8080:80 nginx` | Start detached, map host:container port | | `docker run --rm -it ubuntu bash` | Throwaway interactive shell | | `docker ps` / `docker ps -a` | Running / all containers | | `docker logs -f web` | Follow logs | | `docker exec -it web sh` | Shell into a running container | | `docker stop web` / `docker rm web` | Stop / remove | | `docker inspect web` | Full JSON details | | `docker stats` | Live CPU and memory |
Images, volumes, networks
| Command | Purpose | |---|---| | `docker build -t app:1.0 .` | Build from a Dockerfile | | `docker images` | List images | | `docker pull` / `docker push` | Registry transfer | | `docker tag app:1.0 repo/app:1.0` | Add a tag | | `docker volume ls` / `docker network ls` | List volumes / networks | | `docker system prune` | Remove unused data (asks first) |
Dockerfile (multi-stage example)
FROM node:20-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/dist ./dist
COPY package*.json ./
RUN npm ci --omit=dev
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]| Instruction | Note | |---|---| | `FROM` | Base image; pin a version, not `latest` | | `COPY` vs `ADD` | Prefer `COPY`; `ADD` also unpacks archives and fetches URLs | | `RUN` | Executes at build time, creates a layer | | `CMD` vs `ENTRYPOINT` | `CMD` is the default, overridable; `ENTRYPOINT` is the fixed executable | | `.dockerignore` | Exclude `node_modules`, `.git`, secrets |
Put rarely-changing steps (dependency install) before frequently-changing ones (source copy) to use the build cache.
docker-compose.yml
services:
api:
build: .
ports: ["8000:8000"]
environment:
DATABASE_URL: postgres://app:secret@db:5432/app
depends_on: [db]
db:
image: postgres:16
environment:
POSTGRES_PASSWORD: secret
volumes: [pgdata:/var/lib/postgresql/data]
volumes:
pgdata:docker compose up -d --build
docker compose logs -f api
docker compose down # add -v to delete volumes tooStop spending an hour tailoring each resume — get a tailored resume and cover letter for this job in seconds.
Tailor my resumeEditorial team
Writes practical guides for Indian job seekers. Part of the HireStraight editorial team. Subscribe via RSS.