docker/run

Run Container

Create and start a new Docker container from an image, with options for interactive mode, port mapping, volume mounting, and environment configuration.

container
lifecycle
docker
run
start

Command

docker run

Explanation

The docker run command is the most fundamental Docker command for creating and starting containers from images. It combines creation and execution in one step. When you run docker run, Docker creates a new container from the specified image, allocates resources, sets up networking, mounts volumes if specified, and starts the container. Common options include -d for detached mode, -it for interactive mode, -p for port mapping, -v for volume mounts, -e for environment variables, and --name to assign a name.

Common Use Cases

  • Start a web server container for development
  • Run a database container locally
  • Execute one-off commands in isolated environments
  • Launch production containers
  • Test applications inside containers

Best Practices

  • Use --name for meaningful container names
  • Use -d for long-running services
  • Set resource limits with --memory and --cpus
  • Clean up containers with --rm when not needed

Common Mistakes to Avoid

  • Forgetting to use -d flag and blocking the terminal
  • Incorrect port mapping using -p flag
  • Not naming containers with --name
  • Running containers without cleaning up after use

Troubleshooting

Problem: Container exits immediately after start

Solution: Check logs with docker logs <container>. The container may lack a foreground process.

Problem: Port already in use

Solution: Change the host port in -p or stop the conflicting container.

Problem: Permission denied for mounted volume

Solution: Check host file permissions or use --user flag.

Examples

Run Nginx in detached mode

docker run -d nginx

Run interactive Ubuntu container

docker run -it ubuntu bash

Map container port 80 to host port 8080

docker run -p 8080:80 nginx

Mount host directory to container

docker run -v /host:/container ubuntu

Set environment variable

docker run -e VAR=value myapp