Top 20 Docker Commands and Use Cases for Beginners: Complete Crash Course
Introduction to Docker
Docker has revolutionized software development and deployment by introducing containerization technology that allows developers to package applications with all their dependencies into lightweight, portable containers. This comprehensive crash course will guide you through the essential Docker concepts, installation process, and the top 20 commands every beginner should master.
What is Docker?
Docker is a containerization platform that enables developers to create, deploy, and run applications in containers. Unlike traditional virtual machines, containers share the host operating system kernel, making them incredibly lightweight and efficient. Think of containers as standardized shipping containers for software – they ensure your application runs consistently across different environments, from development to production.
Key Benefits of Docker:
- Consistency: Applications run the same way everywhere - Efficiency: Containers use fewer resources than virtual machines - Scalability: Easy to scale applications up or down - Isolation: Applications are isolated from each other - Portability: Run anywhere Docker is installed
Docker Architecture
Understanding Docker's architecture is crucial for mastering its commands. Docker follows a client-server architecture with three main components:
1. Docker Client: The command-line interface you use to interact with Docker 2. Docker Daemon: The background service that manages containers 3. Docker Registry: Storage for Docker images (like Docker Hub)
Installing Docker
Installing Docker on Windows
1. Download Docker Desktop: Visit the official Docker website and download Docker Desktop for Windows
2. System Requirements: Ensure you have Windows 10 64-bit or Windows 11
3. Enable WSL 2: Docker Desktop uses Windows Subsystem for Linux 2
4. Installation Process:
`bash
# After downloading, run the installer
# Follow the installation wizard
# Restart your computer when prompted
`
Installing Docker on macOS
1. Download Docker Desktop: Get Docker Desktop for Mac from the official website
2. System Requirements: macOS 10.15 or newer
3. Installation Steps:
`bash
# Download the .dmg file
# Drag Docker to Applications folder
# Launch Docker from Applications
`
Installing Docker on Linux (Ubuntu)
`bash
Update package index
sudo apt-get updateInstall packages to allow apt to use repository over HTTPS
sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg \ lsb-releaseAdd Docker's official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpgSet up stable repository
echo \ "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \ $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/nullInstall Docker Engine
sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.ioVerify installation
sudo docker run hello-world`Post-Installation Setup
`bash
Add your user to docker group (Linux)
sudo usermod -aG docker $USERLog out and back in for changes to take effect
Verify Docker installation
docker --version docker run hello-world`Container Basics
What are Containers?
Containers are lightweight, standalone packages that include everything needed to run an application: code, runtime, system tools, libraries, and settings. They provide process isolation while sharing the host OS kernel.
Images vs Containers
- Docker Image: A read-only template used to create containers - Docker Container: A running instance of an image
Think of an image as a blueprint and a container as a house built from that blueprint.
Container Lifecycle
1. Created: Container is created but not started 2. Running: Container is actively running 3. Paused: Container processes are paused 4. Stopped: Container has stopped running 5. Deleted: Container is removed from the system
Top 20 Essential Docker Commands
1. docker --version
Check your Docker installation and version.`bash
docker --version
Output: Docker version 20.10.8, build 3967b7d
`Use Case: Verify Docker installation and check for updates.
2. docker pull
Download an image from Docker Hub or another registry.`bash
Pull latest Ubuntu image
docker pull ubuntuPull specific version
docker pull ubuntu:20.04Pull from specific registry
docker pull nginx:alpine`Use Case: Download base images before creating containers or building custom images.
3. docker images
List all images stored locally on your system.`bash
docker images
Show all images including intermediate layers
docker images -aFilter images
docker images ubuntu`Use Case: Manage local image storage and verify downloaded images.
4. docker run
Create and start a new container from an image.`bash
Basic run command
docker run ubuntuRun interactively with terminal
docker run -it ubuntu /bin/bashRun in background (detached)
docker run -d nginxRun with port mapping
docker run -p 8080:80 nginxRun with volume mounting
docker run -v /host/path:/container/path ubuntuRun with environment variables
docker run -e MYSQL_ROOT_PASSWORD=secret mysqlRun with custom name
docker run --name my-container nginx`Use Case: Start applications, create development environments, run services.
5. docker ps
List running containers.`bash
Show running containers
docker psShow all containers (including stopped)
docker ps -aShow only container IDs
docker ps -qShow latest created container
docker ps -l`Use Case: Monitor running containers and check container status.
6. docker stop
Stop one or more running containers gracefully.`bash
Stop by container ID
docker stop abc123def456Stop by name
docker stop my-containerStop multiple containers
docker stop container1 container2Stop all running containers
docker stop $(docker ps -q)`Use Case: Gracefully shut down services and applications.
7. docker start
Start one or more stopped containers.`bash
Start stopped container
docker start my-containerStart and attach to container
docker start -a my-containerStart multiple containers
docker start container1 container2`Use Case: Restart previously created containers without losing data.
8. docker restart
Restart running or stopped containers.`bash
Restart container
docker restart my-containerRestart with timeout
docker restart -t 30 my-container`Use Case: Apply configuration changes or recover from container issues.
9. docker rm
Remove one or more containers.`bash
Remove stopped container
docker rm my-containerForce remove running container
docker rm -f my-containerRemove multiple containers
docker rm container1 container2Remove all stopped containers
docker rm $(docker ps -aq)Remove containers automatically after exit
docker run --rm ubuntu echo "Hello World"`Use Case: Clean up unused containers to free disk space.
10. docker rmi
Remove one or more images.`bash
Remove image by name
docker rmi ubuntuRemove image by ID
docker rmi abc123def456Force remove image
docker rmi -f ubuntuRemove multiple images
docker rmi ubuntu nginx mysqlRemove all unused images
docker image prune`Use Case: Free up disk space by removing unused images.
11. docker exec
Execute commands in running containers.`bash
Execute interactive bash session
docker exec -it my-container /bin/bashExecute single command
docker exec my-container ls -laExecute as specific user
docker exec -u root my-container whoamiExecute with environment variables
docker exec -e VAR=value my-container env`Use Case: Debug containers, run maintenance tasks, inspect container contents.
12. docker logs
View container logs.`bash
View logs
docker logs my-containerFollow logs in real-time
docker logs -f my-containerShow last 50 lines
docker logs --tail 50 my-containerShow logs with timestamps
docker logs -t my-containerShow logs since specific time
docker logs --since 2023-01-01 my-container`Use Case: Debug applications, monitor container output, troubleshoot issues.
13. docker inspect
Display detailed information about containers or images.`bash
Inspect container
docker inspect my-containerInspect image
docker inspect ubuntuGet specific information using format
docker inspect --format='#' my-containerInspect multiple objects
docker inspect container1 image1`Use Case: Get detailed configuration, network settings, and metadata.
14. docker build
Build images from Dockerfile.`bash
Build from current directory
docker build .Build with tag
docker build -t my-app:v1.0 .Build with different Dockerfile
docker build -f Dockerfile.prod -t my-app:prod .Build with build arguments
docker build --build-arg VERSION=1.0 -t my-app .Build without cache
docker build --no-cache -t my-app .`Use Case: Create custom images for applications and services.
15. docker push
Upload images to Docker registry.`bash
Push to Docker Hub
docker push username/my-app:latestPush specific tag
docker push username/my-app:v1.0Push to private registry
docker push myregistry.com/my-app:latest`Use Case: Share images with team members or deploy to production.
16. docker network
Manage Docker networks.`bash
List networks
docker network lsCreate network
docker network create my-networkCreate bridge network with subnet
docker network create --driver bridge --subnet=172.20.0.0/16 my-networkConnect container to network
docker network connect my-network my-containerDisconnect container from network
docker network disconnect my-network my-containerRemove network
docker network rm my-networkInspect network
docker network inspect my-network`Use Case: Enable communication between containers, isolate services.
17. docker volume
Manage Docker volumes for persistent data.`bash
List volumes
docker volume lsCreate volume
docker volume create my-volumeInspect volume
docker volume inspect my-volumeRemove volume
docker volume rm my-volumeRemove unused volumes
docker volume pruneUse volume in container
docker run -v my-volume:/data ubuntu`Use Case: Persist data, share data between containers, backup important information.
18. docker cp
Copy files between containers and host system.`bash
Copy from container to host
docker cp my-container:/path/to/file /host/path/Copy from host to container
docker cp /host/path/file my-container:/path/to/Copy directory
docker cp my-container:/app/logs/ ./logs/Copy with archive mode
docker cp -a my-container:/data/ ./backup/`Use Case: Extract logs, backup data, deploy configuration files.
19. docker stats
Display real-time resource usage statistics.`bash
Show stats for all running containers
docker statsShow stats for specific container
docker stats my-containerShow stats without streaming
docker stats --no-streamFormat output
docker stats --format "table #\t#\t#"`Use Case: Monitor resource usage, optimize performance, identify bottlenecks.
20. docker system
Manage Docker system resources.`bash
Show system information
docker system infoShow disk usage
docker system dfClean up unused resources
docker system pruneClean up everything (use with caution)
docker system prune -aClean up with filter
docker system prune --filter "until=24h"`Use Case: Maintain system health, free up disk space, monitor Docker daemon.
Understanding Docker Run in Detail
The docker run command is the most important Docker command as it creates and starts containers. Let's explore its various options:
Basic Syntax
`bash
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
`Common Options Explained
#### Interactive Mode (-i, -t)
`bash
Run container interactively
docker run -it ubuntu bashExplanation:
-i: Keep STDIN open
-t: Allocate pseudo-TTY
`#### Detached Mode (-d)
`bash
Run container in background
docker run -d nginxRun with name
docker run -d --name web-server nginx`#### Port Mapping (-p)
`bash
Map host port 8080 to container port 80
docker run -p 8080:80 nginxMap to specific interface
docker run -p 127.0.0.1:8080:80 nginxMap all ports
docker run -P nginx`#### Volume Mounting (-v, --mount)
`bash
Bind mount
docker run -v /host/path:/container/path ubuntuNamed volume
docker run -v my-volume:/data ubuntuRead-only mount
docker run -v /host/path:/container/path:ro ubuntu`#### Environment Variables (-e, --env)
`bash
Single variable
docker run -e DATABASE_URL=postgres://localhost/mydb my-appMultiple variables
docker run -e VAR1=value1 -e VAR2=value2 my-appEnvironment file
docker run --env-file .env my-app`#### Resource Limits
`bash
Limit memory
docker run -m 512m nginxLimit CPU
docker run --cpus="1.5" nginxLimit CPU shares
docker run --cpu-shares=512 nginx`Introduction to Docker Compose
Docker Compose is a tool for defining and running multi-container Docker applications. It uses YAML files to configure application services and can create and start all services with a single command.
Installing Docker Compose
Docker Compose comes bundled with Docker Desktop. For Linux installations:
`bash
Download Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-composeMake executable
sudo chmod +x /usr/local/bin/docker-composeVerify installation
docker-compose --version`Basic Docker Compose File Structure
Create a docker-compose.yml file:
`yaml
version: '3.8'
services:
web:
build: .
ports:
- "5000:5000"
volumes:
- .:/code
environment:
- FLASK_ENV=development
redis:
image: redis:alpine
ports:
- "6379:6379"
`
Essential Docker Compose Commands
`bash
Start services
docker-compose upStart in background
docker-compose up -dBuild and start
docker-compose up --buildStop services
docker-compose downView running services
docker-compose psView logs
docker-compose logsExecute command in service
docker-compose exec web bashScale services
docker-compose up --scale web=3`Practical Examples and Use Cases
Example 1: Running a Web Server
`bash
Run Nginx web server
docker run -d -p 80:80 --name my-web-server nginxCheck if running
docker psView logs
docker logs my-web-serverStop server
docker stop my-web-server`Example 2: Database Container
`bash
Run MySQL database
docker run -d \ --name my-mysql \ -e MYSQL_ROOT_PASSWORD=secretpassword \ -e MYSQL_DATABASE=myapp \ -p 3306:3306 \ -v mysql-data:/var/lib/mysql \ mysql:8.0Connect to database
docker exec -it my-mysql mysql -u root -p`Example 3: Development Environment
Create a docker-compose.yml for a web application:
`yaml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
volumes:
- .:/app
- /app/node_modules
environment:
- NODE_ENV=development
depends_on:
- db
- redis
db:
image: postgres:13
environment:
- POSTGRES_DB=myapp
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
redis:
image: redis:alpine
ports:
- "6379:6379"
volumes:
postgres_data:
`
Start the environment:
`bash
docker-compose up -d
`
Example 4: Creating Custom Images
Create a Dockerfile:
`dockerfile
Use official Node.js runtime
FROM node:16-alpineSet working directory
WORKDIR /appCopy package files
COPY package*.json ./Install dependencies
RUN npm installCopy application code
COPY . .Expose port
EXPOSE 3000Define command to run app
CMD ["npm", "start"]`Build and run:
`bash
Build image
docker build -t my-node-app .Run container
docker run -p 3000:3000 my-node-app`Example 5: Multi-stage Build
`dockerfile
Build stage
FROM node:16-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run buildProduction stage
FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]`Best Practices and Tips
Container Best Practices
1. Use Official Images: Start with official images from Docker Hub 2. Keep Images Small: Use Alpine Linux variants when possible 3. Single Process: Run one process per container 4. Non-root User: Don't run processes as root inside containers 5. Health Checks: Implement health checks for services
Security Best Practices
`dockerfile
Create non-root user
FROM node:16-alpine RUN addgroup -g 1001 -S nodejs RUN adduser -S nextjs -u 1001Use non-root user
USER nextjsCopy files with correct ownership
COPY --chown=nextjs:nodejs . .`Performance Optimization
1. Use .dockerignore: Exclude unnecessary files 2. Layer Caching: Order Dockerfile instructions efficiently 3. Multi-stage Builds: Reduce final image size 4. Resource Limits: Set appropriate CPU and memory limits
Debugging Tips
`bash
Debug container startup issues
docker run -it --entrypoint /bin/bash my-appCheck container processes
docker exec my-container ps auxMonitor resource usage
docker stats my-containerInspect container configuration
docker inspect my-container`Troubleshooting Common Issues
Container Won't Start
`bash
Check logs for errors
docker logs my-containerRun interactively to debug
docker run -it my-image /bin/bashCheck if ports are already in use
netstat -tulpn | grep :8080`Permission Issues
`bash
Fix file permissions
docker exec -u root my-container chown -R user:group /pathRun as specific user
docker exec -u 1000 my-container command`Network Connectivity
`bash
Check container network
docker network ls docker inspect my-containerTest connectivity
docker exec my-container ping google.com`Storage Issues
`bash
Check disk usage
docker system dfClean up unused resources
docker system pruneRemove unused volumes
docker volume prune`Conclusion
Docker is an essential tool for modern software development and deployment. This crash course has covered the fundamental concepts, installation process, and the top 20 Docker commands that every beginner should master. From basic container operations to advanced multi-container orchestration with Docker Compose, you now have the knowledge to start containerizing your applications.
Remember that mastering Docker takes practice. Start with simple examples and gradually work your way up to more complex multi-container applications. The containerization skills you develop will be invaluable for creating scalable, portable, and maintainable applications.
Key takeaways from this crash course:
1. Docker provides consistent environments across development and production
2. Containers are lightweight and efficient compared to virtual machines
3. The docker run command is your gateway to containerization
4. Docker Compose simplifies multi-container application management
5. Following best practices ensures secure and efficient containerized applications
Continue exploring Docker's ecosystem, including Docker Swarm for orchestration, Docker Registry for image management, and integration with cloud platforms. The containerization journey is just beginning, and Docker provides the foundation for modern DevOps practices and cloud-native development.