docker run

Learn how docker run creates and starts a container from an image, how port publishing and flags work, and how to inspect, stop, and remove a running container

docker run creates a container from an image and starts it. It is the command that turns the sealed package from the build into a running server. It takes the image name, applies the flags that describe how the container should run, and then starts the command the image defines. Every flag on this page changes one aspect of that running container: which ports it publishes, which variables it sees, whether it runs in the foreground or the background, and what happens to it when it stops.

Docker itself is not installed on the machine used to write these docs, so no docker run command on this page was run live here. Every flag and behaviour follows the official Docker command reference, and the Rust server the container runs was compiled and run directly with cargo to prove it works.

Where This Fits

The build produced an image, and an image that never runs is only a file in local storage. docker run is the step that gives it a process, a network identity, and a name. The Dockerfile decided what the container holds, and docker run decides how the container behaves on this machine, on this run, with these ports and these settings.

Think of the image as a printed book and docker run as opening it to read. The book is the same for every reader, but each reading is its own session, with its own place in the room and its own bookmark. Two readers can open the same book at once, and each reading ends without changing the printed pages. A container is one reading of the image, and docker run starts it.

The Smallest Working Version

Start with the image built on the earlier pages, named axum-project:1.0, and the same project behind it. The smallest run command is:

docker run axum-project:1.0

This command creates a container from the image and starts the server in the foreground. The terminal is attached to the container, so the server log appears in the terminal, and the terminal is busy until the container stops. Pressing Ctrl+C sends the stop signal to the container, and the server shuts down.

That form is fine for a first check, but it holds the terminal, so the usual first real command adds two flags:

docker run -d -p 3000:3000 --name axum-server axum-project:1.0

The -d flag runs the container detached, in the background, and prints the container ID when it starts. The -p 3000:3000 flag publishes the container port 3000 on the host port 3000, so a request to the host reaches the server inside the container. The --name axum-server flag gives the container a readable name, so later commands can refer to it by name instead of by ID. A request to http://127.0.0.1:3000/health then returns OK, and a request to http://127.0.0.1:3000/ returns the greeting from the server.

These commands were not run live while writing this page, because Docker is not installed here, but they follow the official Docker command reference exactly.

Working Setup:

If docker run -d -p 3000:3000 --name axum-server axum-project:1.0 prints a container ID, and curl http://127.0.0.1:3000/health returns OK, the container is running and reachable. The next checks are docker ps to see it listed and docker logs axum-server to see its startup line.

Docker Is Not Installed Here:

Every Docker command on this page is written from the official Docker docs, not from a live run on this machine. The Rust server was compiled and run with cargo, and the flags were checked against the official Docker command reference, but no container was started while writing this page.

Understanding the Command Piece by Piece

The command has a shape that stays the same no matter how many flags are added, and each part has one job.

docker run [OPTIONS] IMAGE[:TAG] [COMMAND] [ARG...]

IMAGE is the image to run, and TAG is its version label, which defaults to latest when it is left out. The COMMAND and ARG parts after the image name replace the CMD from the Dockerfile, so the same image can be started with a different command for a one-off job. The options come before the image name, and the most used ones are -d, -p, --name, -e, --env-file, --rm, and -it. Each one is covered below, because each one changes the container in a way a beginner will meet in real work.

The -d flag runs the container in the background

docker run -d axum-project:1.0

The -d flag, short for --detach, starts the container in the background and returns the terminal at once, printing the container ID. Without it, the container runs in the foreground, its output appears in the terminal, and the terminal is busy until the container stops. A server that should keep running after the terminal closes needs -d. A first check that needs to see the startup log as it happens can run without it, and Ctrl+C stops the container.

The -p flag publishes a port

docker run -d -p 3000:3000 axum-project:1.0
docker run -d -p 8080:3000 axum-project:1.0
docker run -d -p 127.0.0.1:3000:3000 axum-project:1.0

The -p flag, short for --publish, maps a host port to a container port, in the form host:container. The first example maps host port 3000 to container port 3000, so the server is reached on the usual port. The second maps host port 8080 to container port 3000, so the same image runs on a different host port, which is how two containers from the same image run side by side without colliding. The third form adds a host address, so the port is published only on 127.0.0.1, the local machine, and not on every network interface of the host.

The order matters and is easy to get backwards. The left side is the host port, the side the outside world reaches. The right side is the container port, the side the server listens on inside the container. The EXPOSE line in the Dockerfile documents the container port, but it does not publish it, and without -p the server runs but nothing outside the container can reach it.

The --name flag gives the container a name

docker run -d --name axum-server axum-project:1.0

The --name flag gives the container a readable name. Without it, Docker assigns a random name, and later commands must use the container ID or that random name. A name must be unique among running and stopped containers, so starting a second container with the same name fails until the first one is removed. The name is how docker logs, docker stop, and docker rm refer to the container, so a clear name is worth choosing at the start.

The -e flag sets one environment variable

docker run -d -p 3000:3000 \
  -e LISTEN_ADDRESS=0.0.0.0:3000 \
  -e RUST_LOG=info \
  axum-project:1.0

The -e flag, short for --env, sets one environment variable inside the container. It can be repeated, once per variable, and a variable set this way overrides any ENV value baked into the image. Writing -e NAME with no value copies the variable from the shell that runs Docker, which is useful for a value that already exists on the host. The full set of variables for this server is four, including two required ones.

The --env-file flag loads variables from a file

docker run -d -p 3000:3000 --env-file .env axum-project:1.0

The --env-file flag loads variables from a file, one KEY=value pair per line, and sets them all inside the container. It is the clean form when the server needs more than a couple of variables, because a long chain of -e flags is hard to read and easy to mistype. The file is read from the host machine, not from inside the image, so it never becomes part of the image. A variable set with -e wins over the same variable in the file, and both win over an ENV value baked into the image.

The --rm flag removes the container when it stops

docker run --rm axum-project:1.0

The --rm flag removes the container automatically when it exits. It is the right flag for a one-off run, a test, or a debugging session, where the container is not meant to be kept. A server that should keep running uses a name and no --rm, so it can be inspected and restarted later. A container started with --rm cannot be restarted after it stops, because it no longer exists, and a fresh docker run is needed instead.

The -it flags attach an interactive terminal

docker run -it --rm axum-project:1.0 sh

The -it flags combine -i, which keeps standard input open, and -t, which allocates a terminal. Together they give an interactive shell inside the container, which is the debugging form. The command after the image name, sh, replaces the CMD from the Dockerfile, so the container starts a shell instead of the server. This form only works on an image that has a shell, which the Debian slim runtime does and a distroless runtime does not. It is also the form that fails most confusingly for beginners, because a container started with sh and no -it exits at once, with no error, since there is no terminal to keep it alive.

Flags Come Before the Image Name:

Every flag belongs before the image name. A flag written after the image name is treated as an argument to the command inside the container, not as a Docker flag, so docker run axum-project:1.0 -d does not run the container in the background. It starts the server with -d as an argument, which the server ignores or rejects. The order is always flags, then image, then command.

The Container Lifecycle

A container has four states, and the commands that move it between them are short. Running docker run creates a container and starts it in one step, but the other commands exist because a container often needs to be inspected, stopped, started again, or removed without rebuilding the image.

docker ps
docker logs axum-server
docker stop axum-server
docker start axum-server
docker rm axum-server

docker ps lists the running containers, with their names, images, ports, and uptime. docker ps -a lists stopped containers too, which is where a container that exited unexpectedly shows up. docker logs axum-server prints the output the container has produced, including the server startup line, and docker logs -f axum-server follows the log as new lines appear. docker stop axum-server sends the stop signal to the container and waits for it to shut down cleanly, up to a timeout, after which it is killed. docker start axum-server starts a stopped container again, with the same flags it was created with. docker rm axum-server deletes a stopped container, and docker rm -f axum-server deletes a running one by stopping it first.

The lifecycle matters because docker run always creates a new container. Running the same docker run command twice creates two containers, not one container started twice, and the second one fails if the first one still holds the name or the port. To restart a container, use docker start with its name. To run a fresh copy, remove the old container first, or use a different name and port.

A Richer Complete Example

The richer example runs the config-driven server from the earlier pages, with all four environment variables, a name, a published port, and a restart policy, in one command.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"
src/main.rs
use axum::{extract::State, routing::get, Json, Router};
use axum_project::config::AppConfig;
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    listen_address: String,
    rust_log: String,
}

async fn status(State(config): State<AppConfig>) -> Json<Status> {
    Json(Status {
        listen_address: config.listen_address.to_string(),
        rust_log: config.rust_log.clone(),
    })
}

#[tokio::main]
async fn main() {
    let _ = dotenvy::dotenv();
    let config = match AppConfig::from_env() {
        Ok(config) => config,
        Err(error) => {
            eprintln!("Configuration error: {error}");
            std::process::exit(1);
        }
    };
    let app = Router::new()
        .route("/", get(status))
        .route("/health", get(|| async { "OK" }))
        .with_state(config.clone());
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

The src/config.rs and src/lib.rs files are the same as in the Dockerfile example, with the same four fields, the same required and optional split, and the same defaults. The server code was compiled and run directly with cargo in the scratch project, with the environment variables set in the shell, and a request to / returned the listen address and log level as JSON while /health returned OK. That run proves the server reads the variables correctly. The container run below passes the same variables in the way Docker does, and the server inside the container reads them the same way, because the container environment is just an environment.

The run command for this server, with the variables set one by one, is:

docker run -d \
  --name axum-server \
  -p 3000:3000 \
  -e DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config \
  -e LISTEN_ADDRESS=0.0.0.0:3000 \
  -e RUST_LOG=info \
  -e JWT_SECRET=test-secret-only-for-local-development \
  --restart unless-stopped \
  axum-project:1.0

The backslashes at the ends of the lines are shell line continuations, so the whole command is one logical line split across several lines for readability. The --restart unless-stopped flag tells Docker to restart the container if it exits unexpectedly or if the Docker daemon restarts, but not if it was stopped deliberately with docker stop. That flag is what makes a server survive a machine reboot without a human starting it again. The database address here names a database on the local machine and carries a password that is only an example for local development, so it is safe to copy for a local test, and it must be replaced with the real address before any real deployment.

The equivalent command with a file is shorter and easier to keep correct:

docker run -d --name axum-server -p 3000:3000 --env-file .env --restart unless-stopped axum-project:1.0

The .env file holds the same four variables, one per line, and it must be kept out of version control, because it holds the database password and the signing secret. The file is read from the host machine at container start, and it never becomes part of the image.

After the container starts, the checks are the same in both forms. docker ps shows the container running, docker logs axum-server shows the startup line with the listen address, and curl http://127.0.0.1:3000/ returns the listen address and log level as JSON. If the container is not listed in docker ps, docker ps -a shows it stopped, and docker logs axum-server shows why it stopped, which for this server is usually a missing required variable, named in the error message.

Overriding the Command for a One-Off Job

The command after the image name replaces the CMD from the Dockerfile, and that is how the same image is used for a job other than serving. A container started with a shell instead of the server runs the shell, does its job, and exits, and with --rm it cleans itself up.

docker run --rm -it axum-project:1.0 sh

This starts a shell in a fresh container from the same image, in the foreground, with the terminal attached. The prompt appears inside the container, and commands typed there run inside it. Typing exit ends the shell, the container stops, and --rm removes it. The server never runs in this container, because the sh command replaced the CMD that would have started it.

The same idea works for a non-interactive check. A container started with a single command runs it and exits, which is useful for verifying a file exists inside the image:

docker run --rm axum-project:1.0 ls /usr/local/bin/

The listing shows the binary in /usr/local/bin, which proves the COPY --from=builder line put it where the Dockerfile said it would. The container is removed when the command finishes, so no cleanup is needed. This form only works when the image has the command being run, so ls works on the Debian slim runtime and fails on a distroless runtime, which has no ls at all.

Run Creates, Start Restarts:

docker run always creates a new container, and docker start restarts a stopped one. A second docker run with the same --name fails, because the name is taken, and a second docker run with the same -p port fails, because the port is taken. Use docker start to bring a stopped container back, and use docker run only when a fresh container is wanted.

Port Publishing in Depth

Port publishing is the part of docker run that beginners get wrong most often, because three different ideas share the word port. The server listens on a port inside the container, which is the container port, 3000 in this cluster. The Dockerfile documents that port with EXPOSE 3000, which changes nothing about the network. The -p flag publishes a host port to that container port, and only the published port is reachable from outside the container.

A container with no -p flag runs its server, and the server is reachable from inside the container network, but not from the host. A container with -p 3000:3000 is reachable from the host on port 3000. A container with -p 8080:3000 is reachable from the host on port 8080, while the server inside still listens on 3000. Two containers from the same image can run side by side with -p 3000:3000 and -p 3001:3000, because the host ports differ even though the container ports are the same.

The -P flag, capital P, publishes every port the image exposes to a random host port, which Docker chooses. It is useful for a quick test, but the random port must be read back with docker ps before a request can be made, so the explicit -p form is better for a server that should be reached on a known port.

A common failure is a port that is already in use on the host. Starting a container with -p 3000:3000 while another server already listens on host port 3000 fails with an error about the port being allocated. The fix is to stop the other server, or to publish a different host port, such as -p 3001:3000, and to reach the server on that port instead.

How the Run Flows

The path from a command to a running server has four steps, and each one produces something the next one uses.

docker run -d -p 3000:3000 --name axum-server axum-project:1.0
        |
        v
container created from the image, with flags applied
        |
        v
CMD starts the server as process 1 inside the container
        |
        v
server binds 0.0.0.0:3000, Docker publishes it on host port 3000
        |
        v
curl http://127.0.0.1:3000/health returns OK

The creation step is where the flags take effect. The environment variables are set, the port is published, the name is assigned, and the restart policy is recorded, all before the server starts. The start step runs the command from the image, or the replacement command from the run line. The bind step is the server reading its config and listening, and the publish step is Docker forwarding host traffic to it. A failure at any step shows up in a different place: a creation failure is an error from docker run itself, a start failure is a log line from the container, and a reachability failure is a connection error from curl.

Testing It Without a Docker Daemon

A full test needs Docker, but the server the container runs can be proven on this machine, and each check catches a different failure before the container is ever started.

First, prove the server code compiles, passes its tests, and runs with the same variables the container will pass. The scratch project ran cargo check, cargo test, and cargo build --release for the code on this page, and started the server with LISTEN_ADDRESS=0.0.0.0:3000 and the other three variables set in the shell. A request to / returned the listen address and log level as JSON, and /health returned OK. A run that fails inside the container with a config error is almost always a variable that was not passed, and this check proves the server itself reads them correctly.

Second, check the run command on paper. Every flag comes before the image name, the image name carries its tag, the host port and the container port are in the right order, and the container name is not already in use. A flag after the image name is the most common ordering mistake, and it is caught by reading the command once.

Third, check the environment file, if one is used. It holds one KEY=value pair per line, with no quotes around the values, because --env-file does not process quotes and they become part of the value. It is listed in .gitignore, and it is not copied into the image.

The checks that need Docker are the run itself, the port check with curl, and the log check with docker logs. Those are the first commands to run once Docker is installed, and they are the proof that the container, not just the code, works.

Common Beginner Mistakes

Publishing the ports backwards

# Wrong - host and container ports are swapped
docker run -d -p 3000:8080 axum-project:1.0

The server listens on container port 3000, but this command publishes host port 3000 to container port 8080, where nothing listens, so every request fails to connect. The fix is -p 3000:3000, with the host port on the left and the container port on the right, matching the port the server actually binds.

Running the same container twice

# Wrong - the name and the port are already taken
docker run -d --name axum-server -p 3000:3000 axum-project:1.0
docker run -d --name axum-server -p 3000:3000 axum-project:1.0

The second command fails because the name axum-server is already used and host port 3000 is already published. The fix is docker start axum-server to restart the existing container, or docker rm axum-server to remove it before running a fresh one.

Binding to 127.0.0.1 inside the container

// Wrong - nothing outside the container can reach the server
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();

Inside a container, 127.0.0.1 means the container itself, so the server starts, the container looks healthy, and every request from the host fails to connect. The fix is 0.0.0.0:3000, which listens on every interface of the container, so Docker port publishing can reach it. The config-driven server on this page gets this right by passing LISTEN_ADDRESS=0.0.0.0:3000 at runtime.

Putting flags after the image name

# Wrong - -d after the image is an argument to the server, not a flag
docker run axum-project:1.0 -d

Everything after the image name is the command and its arguments, so -d is handed to the server, which ignores it, and the container runs in the foreground instead. The fix is to put every flag before the image name, in the order flags, image, command.

Forgetting -d and wondering where the terminal went

A container started without -d holds the terminal until it stops, and a beginner who runs it in their only terminal cannot type another command. The fix is Ctrl+C to stop it, or a new terminal tab, and to add -d on the next run. Detached mode is the normal form for a server that should keep running.

Changing a variable on a running container

Environment variables are set when the container is created, and they cannot be changed on a running container. docker exec -e sets a variable for one exec command only, and it does not change the server process. The fix is to stop the container, remove it, and run a fresh one with the new values. A container is cheap to recreate, and that is the intended way to change its configuration.

Secrets on the Command Line Stay in Shell History:

A secret typed as -e JWT_SECRET=... on the command line is saved in the shell history file, where anyone with access to the machine can read it later. The safer form is --env-file, with the file kept out of version control, so the secret never appears on a command line. The file form is the safer way to pass secrets.

Final Complete Example

Everything on this page put together is the project, the image, and the commands that run it, inspect it, and stop it.

Dockerfile
FROM rust:1.100.0-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN cargo fetch
COPY src ./src
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/axum-project /usr/local/bin/axum-project
USER nobody
EXPOSE 3000
CMD ["/usr/local/bin/axum-project"]

Check the code first, then build and run on a machine with Docker:

cargo check
cargo test
docker build -t axum-project:1.0 .
docker run -d --name axum-server -p 3000:3000 --env-file .env --restart unless-stopped axum-project:1.0
docker ps
docker logs axum-server
curl http://127.0.0.1:3000/health

The first two commands were run for this page in the scratch project and passed. The rest follow the official Docker command reference and need Docker installed. When the container is running, the health check returns OK, and the container keeps running until it is stopped:

docker stop axum-server
docker rm axum-server

The stop command asks the server to shut down cleanly, and the rm command deletes the stopped container, freeing its name and its port for the next run.

Summary

docker run is where the image stops being a file and starts being a service, and the flags are the whole difference between a container that works and one that only looks like it works. The image decides what runs, and the run command decides how it runs: which port the host sees, which variables the server reads, whether it runs in the background, and what happens when it stops. Each flag answers one of those questions, and the answers are recorded at creation time, not changed later.

The decision framework is short. Run detached with a name and a published port for a server that should keep running. Pass variables from a file, not from the command line, when there are more than a couple of them or when any of them is a secret. Use --rm for a one-off job and a restart policy for a service. And when a container misbehaves, look at it with docker ps and docker logs before running another one, because the running container usually says what went wrong, and a second container only adds a port conflict to the problem.