TExcelTAD
Home › Docker › Your First Container

Your First Container

The command you will type more than any other is docker run. It takes an image name, and optionally a command, and starts a container from it.

bash
docker run alpine echo "Hello from a container"

Sample output (first run):

text
Unable to find image 'alpine:latest' locally
latest: Pulling from library/alpine
Digest: sha256:4bcff63911fcb4448bd4fdacec207030997caf25e9bea4045fa6c8c44de311d1
Status: Downloaded newer image for alpine:latest
Hello from a container

Run it again and the "Pulling" lines disappear: the image is now cached locally, so the container starts almost instantly.

What docker run actually does

docker run is a shortcut for several steps:

  1. Find the image locally; if it is missing, pull it from a registry (Docker Hub by default).
  2. Create a container: a writable layer on top of the image plus its configuration (name, ports, environment).
  3. Start it: run the image's default command, or the command you gave after the image name.
  4. Attach your terminal to its output (unless you use -d).

When the main process exits, the container stops. A container lives exactly as long as its main process.

python · try it yourself
local_images = {"nginx:1.27"}
containers = []

def docker_run(image, command=None, name=None):
    if ":" not in image:
        image += ":latest"                      # default tag
    if image not in local_images:
        print(f"Unable to find image '{image}' locally -> pulling")
        local_images.add(image)
    name = name or f"container_{len(containers) + 1}"
    container = {"name": name, "image": image, "cmd": command or "(image default)", "state": "created"}
    containers.append(container)
    container["state"] = "running"
    print(f"started {name} from {image}, running {container['cmd']}")
    container["state"] = "exited"               # the command finished
    return container

docker_run("alpine", "echo hi")
docker_run("alpine", "date", name="clock")
docker_run("nginx:1.27", name="web")

for c in containers:
    print(f"{c['name']:<12} {c['image']:<14} {c['state']}")
Unable to find image 'alpine:latest' locally -> pulling
started container_1 from alpine:latest, running echo hi
started clock from alpine:latest, running date
started web from nginx:1.27, running (image default)
container_1  alpine:latest  exited
clock        alpine:latest  exited
web          nginx:1.27     exited

Notice that alpine is only pulled once, and that every docker run creates a new container. Running the same command ten times leaves ten stopped containers behind, unless you add --rm.

The most common options

Option Meaning
-d, --detach Run in the background and print the container ID
--name web Give the container a name instead of a random one like quirky_hopper
--rm Delete the container automatically when it exits
-it -i keeps input open, -t allocates a terminal: use both for an interactive shell
-p 8080:80 Publish container port 80 on host port 8080
-e KEY=value Set an environment variable
-v data:/var/lib/data Mount a volume

Options go before the image name. Everything after the image name is the command to run inside the container, so docker run alpine ls -l passes -l to ls, not to Docker.

python · try it yourself
def parse_run(args):
    opts = {"detach": False, "rm": False, "name": None, "ports": [], "env": []}
    takes_value = {"--name": "name", "-p": "ports", "-e": "env"}
    i = 0
    while i < len(args) and args[i].startswith("-"):
        flag = args[i]
        if flag in ("-d", "--detach"):
            opts["detach"] = True
        elif flag == "--rm":
            opts["rm"] = True
        elif flag in takes_value:
            key = takes_value[flag]
            i += 1
            if isinstance(opts[key], list):
                opts[key].append(args[i])
            else:
                opts[key] = args[i]
        else:
            raise ValueError(f"unknown flag: {flag}")
        i += 1
    opts["image"] = args[i]
    opts["command"] = args[i + 1:]
    return opts

cmd = "-d --name web -p 8080:80 -e MODE=prod nginx:1.27"
print(parse_run(cmd.split()))
print(parse_run("--rm alpine ls -l /etc".split()))
{'detach': True, 'rm': False, 'name': 'web', 'ports': ['8080:80'], 'env': ['MODE=prod'], 'image': 'nginx:1.27', 'command': []}
{'detach': False, 'rm': True, 'name': None, 'ports': [], 'env': [], 'image': 'alpine', 'command': ['ls', '-l', '/etc']}

The second call shows the rule in action: -l ends up in the container's command because it comes after the image name.

A web server in the background

bash
docker run -d --name web -p 8080:80 nginx:1.27
docker ps
curl http://localhost:8080
docker stop web
docker rm web

Sample output:

text
3f1c9a0d7b2e5c41d8e2f6a0b9c7d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8
CONTAINER ID   IMAGE        COMMAND                  STATUS         PORTS                  NAMES
3f1c9a0d7b2e   nginx:1.27   "/docker-entrypoint.…"   Up 3 seconds   0.0.0.0:8080->80/tcp   web
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
web
web

An interactive shell

bash
docker run -it --rm alpine sh

You get a shell prompt inside the container. Look around with ls /, cat /etc/os-release or ps: you will see only the container's own processes. Type exit and, thanks to --rm, the container is deleted.

Tip: docker ps lists running containers; docker ps -a also shows stopped ones. Clean up stopped containers with docker container prune.

Common mistakes

  • The container exits immediately. docker run ubuntu starts bash, finds no terminal and exits at once. Containers need a long-running main process (a server) to stay up, or -it for a shell.
  • Flags after the image name. docker run nginx -p 8080:80 passes -p 8080:80 to nginx instead of publishing a port.
  • "The container name is already in use". Names must be unique, even among stopped containers. Remove the old one (docker rm web) or use --rm.

Test yourself

What happens when you docker run an image that is not on your machine?

  1. Docker fails with an error
  2. Docker pulls it from the registry first, then runs it
  3. Docker builds it from a Dockerfile
  4. Docker runs an empty container

In docker run --rm alpine ls -l, who receives the -l?

  1. Docker
  2. The ls command inside the container
  3. Both
  4. Nobody; it is ignored

When does a container stop?

  1. After 10 minutes
  2. When its main process exits
  3. When you close the Docker Desktop window
  4. Never, until you remove it