Docker Core Concepts
Understanding images and containers is fundamental to working with Docker.
Images vs Containers
| Concept | Description |
|---|---|
| Image | Read-only template with instructions for creating a container |
| Container | Runnable instance of an image |
| Registry | Storage and distribution system for images |
| Layer | Each instruction in Dockerfile creates a layer |
Docker Image Basics
# Pull an image from Docker Hub
docker pull nginx
docker pull nginx:1.25-alpine
# List local images
docker images
docker image ls
# Image details
docker inspect nginx
# Remove an image
docker rmi nginx
docker image rm nginx:1.25-alpine
# Remove unused images
docker image prune
docker image prune -a # Remove all unusedImage Layers
Docker images are built in layers. Each instruction in a Dockerfile creates a new layer.
Image Layer Structure:
+-------------------+
| Application Code | <- Your code (changes frequently)
+-------------------+
| Dependencies | <- npm install, pip install
+-------------------+
| Runtime | <- Node.js, Python
+-------------------+
| Base OS | <- Alpine, Debian, Ubuntu
+-------------------+# View image layers
docker history nginx
# Show layer sizes
docker history --no-trunc nginxContainer Basics
# Create and start a container
docker run nginx
# Run in detached mode (background)
docker run -d nginx
# Run with name
docker run -d --name my-nginx nginx
# Run with port mapping
docker run -d -p 8080:80 nginx
# Run with environment variables
docker run -d -e MYSQL_ROOT_PASSWORD=secret mysql
# Run interactively
docker run -it ubuntu bashContainer Lifecycle
# List running containers
docker ps
# List all containers (including stopped)
docker ps -a
# Stop a container
docker stop my-nginx
# Start a stopped container
docker start my-nginx
# Restart a container
docker restart my-nginx
# Remove a container
docker rm my-nginx
# Remove running container (force)
docker rm -f my-nginx
# Remove all stopped containers
docker container pruneContainer Interaction
# Execute command in running container
docker exec -it my-nginx bash
# View container logs
docker logs my-nginx
docker logs -f my-nginx # Follow logs
docker logs --tail 100 my-nginx
# View container processes
docker top my-nginx
# View resource usage
docker stats
docker stats my-nginx
# Copy files to/from container
docker cp ./file.txt my-nginx:/app/
docker cp my-nginx:/app/file.txt ./Container Inspection
# Full container details
docker inspect my-nginx
# Get specific field
docker inspect --format='{{.NetworkSettings.IPAddress}}' my-nginx
# View port mappings
docker port my-nginx
# View filesystem changes
docker diff my-nginxContainer Best Practices
- One process per container - Run single service per container
- Immutable containers - Don't modify running containers
- Use specific tags - Avoid
latestin production - Clean up regularly - Prune unused resources
- Use restart policies -
--restart unless-stopped
- docker
- images
- containers
- layers
- registry