What is Docker?
Docker is a platform for developing, shipping, and running applications in containers.
Basic Concepts
Images vs Containers
- Image: Read-only template with application code
- Container: Running instance of an image
bash
# Run a container
docker run nginx
# List containers
docker ps
# List all containers
docker ps -aDockerfile
Creating Images
dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]Building Images
bash
docker build -t myapp:1.0 .Docker Compose
Multi-Container Applications
yaml
version: '3.8'
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- mongodb
mongodb:
image: mongo:latest
ports:
- "27017:27017"
volumes:
- mongodb_data:/data/db
volumes:
mongodb_data:Running Compose
bash
# Start services
docker-compose up -d
# Stop services
docker-compose down
# View logs
docker-compose logs -fBest Practices
- 1Use official base images: They're regularly updated
- 2Minimize layers: Combine RUN commands
- 3Use multi-stage builds: Reduce image size
- 4Don't run as root: Use USER directive
- 5Use .dockerignore: Exclude unnecessary files
Multi-Stage Build
dockerfile
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Production stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY package*.json ./
RUN npm ci --only=production
CMD ["node", "server.js"]Volumes
Persisting Data
bash
# Named volume
docker run -v mydata:/app/data myapp
# Bind mount
docker run -v $(pwd)/data:/app/data myappNetworks
Container Communication
bash
# Create network
docker network create mynetwork
# Connect containers
docker run --network mynetwork --name web myapp
docker run --network mynetwork --name api myapi
# Containers can now communicate using service namesDocker Commands Reference
bash
# Images
docker images
docker rmi <image>
docker pull <image>
docker push <image>
# Containers
docker ps
docker stop <container>
docker start <container>
docker rm <container>
docker logs <container>
docker exec -it <container> sh
# System
docker system prune
docker statsSecurity
- 1Scan images: Check for vulnerabilities
- 2Use specific tags: Avoid 'latest' tag
- 3Limit resources: Prevent resource abuse
- 4Run as non-root: Use USER directive
- 5Keep updated: Regular security updates
Conclusion
Docker simplifies application deployment and ensures consistency across environments.