How to run a Docker container?
· Category: Docker
Short answer
The docker run command creates and starts a container from an image. You can configure networking, storage, environment variables, and resource limits using command-line flags.
Steps
- Identify the image name and tag.
- Map ports with
-p host:container. - Mount volumes with
-v host:container. - Set environment variables with
-e KEY=VALUE. - Run detached with
-dor interactively with-it.
Example
docker run -d --name api-server -p 8080:8080 -v $(pwd)/data:/data -e DATABASE_URL=postgres://db:5432/app --restart unless-stopped myapp:v1.0
Run an interactive shell:
docker run -it --rm ubuntu:22.04 /bin/bash
Tips
- Use
--rmfor one-off containers to auto-remove them after exit. - Use
--nameto assign a memorable name for easier management. - Use
--networkto attach the container to a specific Docker network. - Use
--memoryand--cpusto limit container resources.
Common issues
- Port conflicts occur when the host port is already in use.
- Permission errors with volumes can be fixed by matching host/container UIDs.
- Missing environment variables cause application startup failures.