Foreground and Detached

Running a Container in the Foreground and Detached

docker run creates a container and starts it, pulling the image if needed. By default it runs in the foreground, attached to your terminal until the main process exits; --rm deletes the container afterwards:

A foreground container that prints and exitsShell
docker run --rm alpine:3 sh -c 'for i in 1 2 3; do echo "tick $i"; sleep 1; done'
Output
tick 1
tick 2
tick 3

A database should keep running, so start it detached with -d. Docker 514 prints the container's ID and returns:

Starting PostgreSQL in the backgroundShell
docker run -d -e POSTGRES_PASSWORD=booknest postgres:18
docker ps --format 'table {{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}\t{{.Names}}'
Output
3f334c24c1f29ff358ad82603bb418f9339566eeee7250b5705b5eaf546312d9
CONTAINER ID   IMAGE         STATUS                  PORTS      NAMES
3f334c24c1f2   postgres:18   Up Less than a second   5432/tcp   stoic_shtern

5432/tcp is a port the image declares, not yet reachable from the host (Publishing Ports to the Host). With no --name, Docker invented stoic_shtern. -it gives an interactive terminal; Ctrl+P, Ctrl+Q detaches from it without stopping it. A container lives exactly as long as its main process, which is why docker run -d alpine:3 exits at once: its default command is a shell with no input.