How to Create a Container in Docker: Simple Steps
To create a container in Docker, use the
docker run command followed by the image name. This command downloads the image if needed and starts a new container from it.Syntax
The basic syntax to create a container is:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Here, docker run creates and starts a container from the specified IMAGE. You can add OPTIONS to customize the container behavior, and optionally specify a COMMAND to run inside the container.
bash
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Example
This example creates and runs a container from the official nginx image. It starts a web server inside the container.
bash
docker run --name mynginx -d -p 8080:80 nginx
Output
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
...
Digest: sha256:...
Status: Downloaded newer image for nginx:latest
c3f279d17e0a4e5a8f8b8a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1a1
Common Pitfalls
Common mistakes when creating containers include:
- Not specifying the image name correctly, causing errors.
- Forgetting to use
-dto run the container in detached mode, which keeps it running in the background. - Not mapping ports with
-p, so you cannot access services running inside the container. - Trying to run a container without pulling the image first, though
docker runusually pulls automatically.
bash
docker run nginx # This runs in foreground and blocks terminal docker run -d nginx # Runs in background docker run -p 8080:80 nginx # Maps port 8080 on host to 80 in container
Quick Reference
Here is a quick cheat sheet for creating Docker containers:
| Option | Description |
|---|---|
| -d | Run container in background (detached mode) |
| --name | Assign a name to the container |
| -p | Map host port to container port |
| -it | Run container interactively with a terminal |
| --rm | Automatically remove container when it stops |
Key Takeaways
Use
docker run with an image name to create and start a container.Add
-d to run containers in the background.Map ports with
-p to access container services from your host.Name containers with
--name for easier management.Docker pulls the image automatically if it is not present locally.