Back to Home
Docker
Fundamental Docker commands for container management
containersimagesrunbasic
Docker Basics
Essential Docker commands for everyday container management.
Container Lifecycle
# Run a container
docker run nginx
# Run in detached mode
docker run -d nginx
# Run with port mapping
docker run -d -p 8080:80 nginx
# Run with name
docker run -d --name my-nginx nginx
# Run with environment variables
docker run -d -e MY_VAR=value nginx
# Run with volume mount
docker run -d -v /host/path:/container/path nginx
Managing Containers
# List running containers
docker ps
# List all containers
docker ps -a
# Stop a container
docker stop container_name
# Start a stopped container
docker start container_name
# Restart a container
docker restart container_name
# Remove a container
docker rm container_name
# Force remove running container
docker rm -f container_name
Container Interaction
# Execute command in container
docker exec -it container_name bash
# View container logs
docker logs container_name
# Follow logs
docker logs -f container_name
# Copy files to/from container
docker cp file.txt container_name:/path/
docker cp container_name:/path/file.txt ./
Example Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Building and Running from Dockerfile
# Build image from Dockerfile in current directory
docker build -t my-app:latest .
# Build with a specific Dockerfile
docker build -f Dockerfile.prod -t my-app:prod .
# Build with build arguments
docker build --build-arg NODE_ENV=production -t my-app .
# Build without cache
docker build --no-cache -t my-app .
# Run the built image
docker run -d -p 3000:3000 --name my-app my-app:latest
# Tag and push to registry
docker tag my-app:latest registry.example.com/my-app:latest
docker push registry.example.com/my-app:latest
Cleanup
# Remove all stopped containers
docker container prune
# Remove unused images
docker image prune
# Remove all unused resources (containers, images, networks, volumes)
docker system prune -a
# Check disk usage
docker system df