How to Run a Docker Image as a Container
TLDR
Use docker run to start a container from an image. You can map ports, set environment variables, and control the container's lifecycle with various flags.
Running a Docker image as a container is the core of container-based development. Whether you're testing locally or deploying to production, understanding how to use docker run gives you flexibility and control.
Basic Usage
The simplest way to run a container is:
docker run nginx:alpine
This starts a new container from the nginx:alpine image. By default, it runs in the foreground and shows the container's output.
Running in Detached Mode
To run the container in the background, add the -d flag:
docker run -d nginx:alpine
Now the container runs in the background, and you get the container ID.
Mapping Ports
To access services inside the container, map ports from the host to the container:
docker run -d -p 8080:80 nginx:alpine
This maps port 8080 on your host to port 80 in the container. You can now access the service at http://localhost:8080.
Passing Environment Variables
You can pass environment variables to configure your app:
docker run -e ENV=production my-app:latest
This sets the ENV variable inside the container.
Mounting Volumes
To persist data or share files, mount a host directory:
docker run -v $(pwd)/data:/app/data my-app:latest
This mounts the local ./data directory to /app/data in the container.
Stopping and Removing Containers
List running containers:
docker ps
Stop a container:
docker stop <container_id>
Remove a container:
docker rm <container_id>
Best Practices
- Use descriptive container names with
--name. - Clean up stopped containers to save resources.
- Use environment variables and volumes for configuration and data.
With these techniques, you can run, manage, and debug containers efficiently in any environment.
Good luck with your project!
Related Resources
- Docker Run vs Docker Start — understand the difference
- Docker Image vs Container — key concepts
- Docker Compose: Ports vs Expose — port mapping
- Pass Environment Variables to Docker Containers — configure at runtime
- Introduction to Docker Guide — learn Docker from scratch
- Docker Quiz — test your knowledge
We earn commissions when you shop through the links below.
DigitalOcean
Cloud infrastructure for developers
Simple, reliable cloud computing designed for developers
DevDojo
Developer community & tools
Join a community of developers sharing knowledge and tools
Acronis
The most secure backup
Acronis: the most secure backup solution for your data
Pluralsight
Technology skills platform
Expert-led courses in software development, IT ops, data, and cybersecurity
Want to support DevOps Daily and reach thousands of developers?
Become a SponsorFound an issue?