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

  1. Identify the image name and tag.
  2. Map ports with -p host:container.
  3. Mount volumes with -v host:container.
  4. Set environment variables with -e KEY=VALUE.
  5. Run detached with -d or 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 --rm for one-off containers to auto-remove them after exit.
  • Use --name to assign a memorable name for easier management.
  • Use --network to attach the container to a specific Docker network.
  • Use --memory and --cpus to 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.