How to Start a Container in Docker: Simple Commands and Examples
To start a container in Docker, use
docker run to create and start a new container from an image, or use docker start to start an existing stopped container. The docker run command combines creation and starting, while docker start only starts containers that already exist.Syntax
The main commands to start containers in Docker are:
- docker run [OPTIONS] IMAGE [COMMAND] [ARG...]: Creates and starts a new container from the specified image.
- docker start [OPTIONS] CONTAINER: Starts an existing stopped container by its name or ID.
Options can customize container behavior, like -d to run in background (detached mode) or -p to map ports.
bash
docker run [OPTIONS] IMAGE [COMMAND] [ARG...] docker start [OPTIONS] CONTAINER
Example
This example shows how to start a new container running the nginx web server in detached mode and then start a stopped container.
bash
# Start a new nginx container in detached mode $ docker run -d --name mynginx -p 8080:80 nginx # Stop the container $ docker stop mynginx # Start the stopped container again $ docker start mynginx
Output
a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6
mynginx
Common Pitfalls
Common mistakes when starting containers include:
- Using
docker starton a container that does not exist or is already running. - Forgetting to map ports with
-pwhen running services that need network access. - Not using
-dto run containers in the background, causing the terminal to be blocked.
Example of wrong and right usage:
bash
# Wrong: Trying to start a container that does not exist $ docker start unknown_container Error: No such container: unknown_container # Right: Run a new container first $ docker run -d --name known_container nginx # Then start it if stopped $ docker start known_container
Output
Error: No such container: unknown_container
<container_id>
known_container
Quick Reference
| Command | Description | Example |
|---|---|---|
| docker run | Create and start a new container | docker run -d -p 80:80 nginx |
| docker start | Start an existing stopped container | docker start mycontainer |
| docker stop | Stop a running container | docker stop mycontainer |
| docker ps | List running containers | docker ps |
| docker ps -a | List all containers | docker ps -a |
Key Takeaways
Use
docker run to create and start a new container from an image.Use
docker start to start a container that was previously stopped.Remember to map ports with
-p if your container needs network access.Use
-d option to run containers in the background.Check container status with
docker ps before starting or stopping.