Docker CLI, Container Lifecycle & Dockerfile Directives Cheat Sheet
Essential reference for container run, build, compose, network, volume, and image optimization commands.
Table of Contents
Container Lifecycle & Execution
Commands for starting, inspecting, and managing live container instances.
| Command | Description | Common Example |
|---|---|---|
| docker run -d --name <name> -p <host>:<cont> <img> | Run container in background with port mapping | docker run -d -p 8080:80 --name web nginx:alpine |
| docker exec -it <container> <cmd> | Execute interactive command inside running container | docker exec -it web sh |
| docker logs -f --tail 100 <container> | Stream real-time container log output | docker logs -f --tail 50 web |
| docker stop / start / restart <container> | Control container execution state | docker restart redis-cache |
| docker rm -f <container> | Forcefully stop and remove a container | docker rm -f web |
Image Building & Registry
Commands for compiling Dockerfiles and pushing images.
| Command | Description | Common Example |
|---|---|---|
| docker build -t <tag> . | Build image from Dockerfile in current directory | docker build -t myapp:v1.2 . |
| docker images | List all locally cached Docker images | docker images -a |
| docker rmi <image_id> | Delete local image by ID or name | docker rmi myapp:v1.0 |
| docker tag <src> <target> | Tag image for registry push | docker tag app:v1 registry.hub.docker.com/u/app:v1 |
Disk Space & Resource Cleanup
Reclaim gigabytes of disk space occupied by dangling build caches and stopped containers.
| Command | Description | Risk Level |
|---|---|---|
| docker system prune | Remove stopped containers, dangling images, and unused networks | Safe |
| docker system prune -a --volumes | Remove ALL unused images and anonymous volumes | Destructive |
| docker builder prune -a | Clear BuildKit build cache | Safe |
Interactive Client-Side Tools for this Guide
Test and run these patterns directly inside your browser with zero server uploads:
Frequently Asked Questions
What is the difference between CMD and ENTRYPOINT in Dockerfile?
ENTRYPOINT sets the default executable for the container that should always run, while CMD defines default arguments that can be easily overridden by arguments passed to docker run.
How do I reduce Docker image size?
Use Alpine Linux base images (e.g. node:alpine), leverage multi-stage builds to discard build tools from the final layer, and combine RUN commands with && to minimize layer count.