Running Containers

The docker run command creates and starts a container, with flags to control how it behaves.

Syntaxdocker run [options] IMAGE [command] [args]

docker run is the most-used Docker command. It combines two steps: create a container from an image, then start it.

Useful flags

  • -d — detached, runs in the background.
  • -it — interactive terminal, for shells and prompts.
  • --name — give the container a memorable name.
  • --rm — automatically remove the container when it exits.
  • -p — publish a port to the host.

Interactive containers

Combine -it with a shell to explore inside an image. When you exit the shell, the container stops.

Example

Example · bash
# Open an interactive shell inside an Ubuntu container
docker run -it --rm ubuntu bash

# Run a one-off command and remove the container after
docker run --rm alpine echo "Hello from a container"

When to use it

  • A developer runs a PostgreSQL container locally to get a fresh database for integration tests without installing Postgres on their machine.
  • A QA engineer uses docker run to spin up a specific version of a service to reproduce a bug reported on that version.
  • An ops team uses docker run with resource limits to ensure a batch job cannot consume more than 2 CPU cores or 1 GB of RAM.

More examples

Run a container interactively

Starts an Ubuntu container with an interactive terminal; --rm cleans it up automatically on exit.

Example · bash
docker run -it --rm ubuntu bash

Run with resource limits

Runs a container in the background capping it to 512 MB of RAM and 1 CPU core to prevent resource contention.

Example · bash
docker run -d \
  --name api \
  --memory 512m \
  --cpus 1.0 \
  -p 3000:3000 \
  myapp:latest

Run with named volume and env vars

Starts a PostgreSQL container with environment-based configuration and a named volume for data persistence.

Example · bash
docker run -d \
  --name postgres \
  -e POSTGRES_PASSWORD=secret \
  -e POSTGRES_DB=mydb \
  -v pgdata:/var/lib/postgresql/data \
  postgres:16-alpine

Discussion

  • Be the first to comment on this lesson.