You run a container from an image using the docker run command, which creates a writable container layer from the image and executes its default command or a specified override.
The docker run command is the primary way to start a container from a Docker image. It creates a new container instance from the specified image, adds a writable layer on top, and executes the container's default command (defined by CMD or ENTRYPOINT in the Dockerfile) or a command you provide. The container runs in isolation but can be configured to expose ports, mount volumes, set environment variables, and define resource limits through various flags.
When you run docker run, Docker first checks if the specified image exists locally. If not, it attempts to pull the image from a configured registry (like Docker Hub). It then creates a container from that image, assigns a unique ID and name (or uses a generated one), and finally starts the container. The container runs until its main process exits, at which point the container stops. The --restart flag can automatically restart the container if it exits.
The -d or --detach flag runs the container in the background, returning control to the terminal. Without this flag, the container runs in the foreground, and its logs are printed to your terminal. The -it combination (interactive + pseudo-TTY) is essential for running shells inside containers, allowing you to debug or explore the container's filesystem.
-d, --detach: Run container in background and print container ID
-p, --publish: Publish a container's port(s) to the host (format: host:container)
-v, --volume: Bind mount a volume (format: source:destination)
--name: Assign a name to the container for easier reference
-e, --env: Set environment variables
--rm: Automatically remove the container when it exits (cleanup)
-it: Allocate a pseudo-TTY and keep STDIN open (interactive mode)
--restart: Restart policy (no, always, on-failure, unless-stopped)
--memory, --cpus: Resource limits
The --rm flag is particularly useful for short-lived containers like development servers or test runs, as it automatically deletes the container when it stops, preventing accumulation of stopped containers on your system. Without this flag, containers persist in the stopped state, which you can view with docker ps -a. For production services like databases or web servers, you typically omit --rm so the container remains available after restarts.