Top 20 Docker Commands for Beginners: Complete Guide

Master Docker containerization with this comprehensive crash course covering essential commands, installation, and practical use cases for beginners.

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 update

Install packages to allow apt to use repository over HTTPS

sudo apt-get install \ apt-transport-https \ ca-certificates \ curl \ gnupg \ lsb-release

Add Docker's official GPG key

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

Set 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/null

Install Docker Engine

sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io

Verify installation

sudo docker run hello-world `

Post-Installation Setup

`bash

Add your user to docker group (Linux)

sudo usermod -aG docker $USER

Log 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 ubuntu

Pull specific version

docker pull ubuntu:20.04

Pull 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 -a

Filter 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 ubuntu

Run interactively with terminal

docker run -it ubuntu /bin/bash

Run in background (detached)

docker run -d nginx

Run with port mapping

docker run -p 8080:80 nginx

Run with volume mounting

docker run -v /host/path:/container/path ubuntu

Run with environment variables

docker run -e MYSQL_ROOT_PASSWORD=secret mysql

Run 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 ps

Show all containers (including stopped)

docker ps -a

Show only container IDs

docker ps -q

Show 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 abc123def456

Stop by name

docker stop my-container

Stop multiple containers

docker stop container1 container2

Stop 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-container

Start and attach to container

docker start -a my-container

Start 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-container

Restart 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-container

Force remove running container

docker rm -f my-container

Remove multiple containers

docker rm container1 container2

Remove 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 ubuntu

Remove image by ID

docker rmi abc123def456

Force remove image

docker rmi -f ubuntu

Remove multiple images

docker rmi ubuntu nginx mysql

Remove 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/bash

Execute single command

docker exec my-container ls -la

Execute as specific user

docker exec -u root my-container whoami

Execute 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-container

Follow logs in real-time

docker logs -f my-container

Show last 50 lines

docker logs --tail 50 my-container

Show logs with timestamps

docker logs -t my-container

Show 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-container

Inspect image

docker inspect ubuntu

Get specific information using format

docker inspect --format='#' my-container

Inspect 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:latest

Push specific tag

docker push username/my-app:v1.0

Push 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 ls

Create network

docker network create my-network

Create bridge network with subnet

docker network create --driver bridge --subnet=172.20.0.0/16 my-network

Connect container to network

docker network connect my-network my-container

Disconnect container from network

docker network disconnect my-network my-container

Remove network

docker network rm my-network

Inspect 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 ls

Create volume

docker volume create my-volume

Inspect volume

docker volume inspect my-volume

Remove volume

docker volume rm my-volume

Remove unused volumes

docker volume prune

Use 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 stats

Show stats for specific container

docker stats my-container

Show stats without streaming

docker stats --no-stream

Format 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 info

Show disk usage

docker system df

Clean up unused resources

docker system prune

Clean up everything (use with caution)

docker system prune -a

Clean 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 bash

Explanation:

-i: Keep STDIN open

-t: Allocate pseudo-TTY

`

#### Detached Mode (-d) `bash

Run container in background

docker run -d nginx

Run 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 nginx

Map to specific interface

docker run -p 127.0.0.1:8080:80 nginx

Map all ports

docker run -P nginx `

#### Volume Mounting (-v, --mount) `bash

Bind mount

docker run -v /host/path:/container/path ubuntu

Named volume

docker run -v my-volume:/data ubuntu

Read-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-app

Multiple variables

docker run -e VAR1=value1 -e VAR2=value2 my-app

Environment file

docker run --env-file .env my-app `

#### Resource Limits `bash

Limit memory

docker run -m 512m nginx

Limit CPU

docker run --cpus="1.5" nginx

Limit 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-compose

Make executable

sudo chmod +x /usr/local/bin/docker-compose

Verify 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 up

Start in background

docker-compose up -d

Build and start

docker-compose up --build

Stop services

docker-compose down

View running services

docker-compose ps

View logs

docker-compose logs

Execute command in service

docker-compose exec web bash

Scale 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 nginx

Check if running

docker ps

View logs

docker logs my-web-server

Stop 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.0

Connect 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-alpine

Set working directory

WORKDIR /app

Copy package files

COPY package*.json ./

Install dependencies

RUN npm install

Copy application code

COPY . .

Expose port

EXPOSE 3000

Define 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 build

Production 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 1001

Use non-root user

USER nextjs

Copy 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-app

Check container processes

docker exec my-container ps aux

Monitor resource usage

docker stats my-container

Inspect container configuration

docker inspect my-container `

Troubleshooting Common Issues

Container Won't Start

`bash

Check logs for errors

docker logs my-container

Run interactively to debug

docker run -it my-image /bin/bash

Check 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 /path

Run as specific user

docker exec -u 1000 my-container command `

Network Connectivity

`bash

Check container network

docker network ls docker inspect my-container

Test connectivity

docker exec my-container ping google.com `

Storage Issues

`bash

Check disk usage

docker system df

Clean up unused resources

docker system prune

Remove 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.

Tags

  • Beginner Tutorial
  • Containerization
  • DevOps
  • docker

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Top 20 Docker Commands for Beginners: Complete Guide