Docker Containers
Source: docker container official document
Docker Containers
docker run
The docker run command starts a new container and runs a command within it, pulling the image if needed and starting the container.
1 | docker container run [OPTIONS] <IMAGE> [COMMAND] [ARG...] |
Key Options:
-i, --interactive: Keep STDIN open even if not attached-t, --tty: Allocate a pseudo-TTY-d, --detach: Run container in the background--name NAME: Specify a custom identifier for a container--rm: Automatically remove the container when it exits-p HOST:CONTAINER: Create a port mapping between the host and the container
Network Options:
--network bridge: Default bridge network--network host: Use host's network stack--network none: Disable networking
Restart Policies:
--restart no: Don't restart (default)--restart always: Always restart--restart unless-stopped: Restart unless manually stopped
Common Patterns
Run the image with a bash process as the main process in the background:
1 | docker run --rm -d -i --name <CONTAINER> <IMAGE> bash |
where -i keeps STDIN open. This keeps bash open since it is waiting for input.
Run the image with a bash process as the main process interatively:
1 | docker run --rm -it --name <CONTAINER> <IMAGE> bash |
docker exec
The docker exec command runs a new command in a running container. The command you specify with docker exec only runs while the container's primary process (PID 1) is running.
1 | docker exec [OPTIONS] <CONTAINER> <COMMAND> [ARG...] |
Key Options:
-i, --interactive: Keep STDIN open-t, --tty: Allocate pseudo-TTY-d, --detach: Run in background--workdir DIR: Set working directory--user USER: Run as specified user
Access running container:
1 | docker exec -it <CONTAINER> bash |
Container Management
List containers:
1 | docker container ls # Running containers |
Control containers:
1 | docker container start <CONTAINER> # Start stopped container |
Remove containers:
1 | docker container rm <CONTAINER> # Remove stopped container |
Container information:
1 | docker container inspect <CONTAINER> # Full container details |
Resource inspection:
1 | docker network ls # List networks |
Detach from container: Ctrl+P, Ctrl+Q (leaves container running)
The main process (PID 1) controls container lifecycle. The stop command sends SIGTERM and waits 10s before sending SIGKILL. Commands run via exec are additional processes that don't affect the main container process.