Track
If you’re wondering how to run a Docker image, you’re not alone. Whether you just pulled an image from Docker Hub or built one yourself, running it is the key step that brings your application to life.
This tutorial is your beginner-friendly guide to the docker run
command and beyond. You’ll learn:
- What Docker images and containers actually are.
- How to run an image using different options.
- And how to stop, remove, and troubleshoot containers like a pro.
By the end, you’ll be confident launching your own containers and understanding exactly what’s happening under the hood.
Understanding Docker Images and Containers
Before getting into command examples, let’s understand Docker images and containers in simple terms.
If you’re already familiar with these terms, feel free to skip to the next section!
What is a Docker image?
A Docker image is an immutable blueprint for your app. It defines everything your container needs: the code, libraries, environment, and configs. Once you have an image, you can use it to spin up one container or a hundred. It stays consistent every time.
So, where do images come from? Dockerfile builds them. A Dockerfile is where you define what base image to use, what dependencies to install, and how your app should run.
Once your Dockerfile is ready, you run the docker build
command. This command follows the steps in the file and turns them into a reusable image.
What is a Docker container?
A Docker container is the active version of a Docker image. It allows your application to run in its own isolated environment, ensuring consistent behaviour regardless of the host system.
It follows the “build once, run anywhere” approach, so you don’t have to manually set up the environment each time.
Image vs container
The following table compares an image and a container side-by-side:
Image |
Container |
An image is a standardized package that includes all the files, binaries, libraries, and configurations to run a container. |
A runtime instance of an image. |
An image is immutable. That means it cannot change until it is rebuilt. |
The container is mutable. You can modify it while it’s running, install new packages, or change configuration files. |
A Dockerfile (a set of instructions to build an image) creates an image. |
An image creates a container. |
Your computer stores image files. |
A container runs in your memory. |
If you're brand new to containerization, our Introduction to Docker course walks you through the core concepts with hands-on examples.
The docker run Command
When you execute the docker run
command, you’re telling Docker to spin up a new container based on an image.
In plain terms, you’re launching a program inside an isolated environment. That program could be anything, a simple web app or a full-blown service with multiple processes.
Basic syntax
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
[OPTIONS]
- Extra flags to customize how the container runsIMAGE
- The Docker image name[COMMAND]
- (Optional) Overrides the default command in the image.[ARG...]
- (Optional) Arguments.
Common flags and options
-d
: Detached mode: runs containers in the background-p
: Port mapping: To access a service (like an API or web app) from your browser, you need to expose a port. Example:-p 3000:3000
maps your machine’s port 3000 to the container’s port 3000.--name
: Docker gives the container a default name, but you can use this flag to give it a new name.-v
: You use this to keep any data separate from the container itself, ensuring it stays even if the container is stopped or deleted.--rm
: When the container stops, this flag automatically deletes it.-e
: Use it to pass in database passwords or API keys without hardcoding them in your app.
Running interactive vs detached containers
Docker runs containers in two ways: interactive mode (-it
) and detach mode (-d
). Each mode has specific use cases depending on your goals.
-it
: Interactive mode: If you want to work directly inside a container using the terminal, you can use the-it
flag. It puts the container in interactive mode, so you can type commands, see the output, and work in real-time.-i
: Keeps the input open so you can type commands into the container-t
: Gives you a terminal-like interface inside the container-d
: Detached mode: It runs the container in the background, so your terminal is free for other tasks.
Keep key commands and best practices at your fingertips with our Docker for Data Science Cheat Sheet.
Pulling and Running Docker Images
Now that you know the syntax of the docker run
command, this section will show you how to create custom images and run them.
Using images from Docker Hub
Docker Hub is like an online library for container images. You can grab pre-built ones or upload yours to share with others. It supports both public and private repositories, so you can share images openly with the community or implement access controls for your internal teams.
Running custom images
To run a Docker image, you’ll first need to build it using a Dockerfile. Then, you can run it locally or push it to the Docker Hub to share.
So, first let's create a Dockerfile. Here’s a sample:
# Use official Python base image
FROM python:3.11-slim
# Set working directory in the container
WORKDIR /app
# Copy requirements file and install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the app code
COPY . .
EXPOSE 5000
# Set default command
CMD ["python", "app.py"]
What does the above Dockerfile mean?
FROM python:3.11-slim
: base image with python 3.11 versionWORKDIR /app
: Sets/app
as the working directory inside the container.COPY requirements.txt .
: moves all dependencies from local machine to the container’s app directory.RUN pip install --no-cache-dir -r requirements.txt
: installs dependencies in requirements.txt.COPY . .
: copies current working directories code (apps, config files, and others) into container’s app directory.- CMD ["python", "app.py"]: runs app.py when starting a container from this image.
Step 1. Build Dockerfile
Let’s see what happens when you build this Dockerfile.
- Execute the following command:
docker build -t my-python-app .
Note: For this command to work, you should first have Docker set up in your system; this guide helps you do that.
Here’s what happens behind the scenes when you execute the build command:
- Docker reads the Dockerfile
- The Python base image is pulled from Docker Hub
- The working directory is set to
/app
. - The
requirements.txt
is copied into the container. - Dependencies are installed using
pip install
. - The rest of your code is copied into
/app
. - The final image is tagged as
my-python-app
.
Step 2: Run Dockerfile
Once your image is built, you can execute it using:
docker run -p 5000:5000 my-python-app
Here is what happens when you run it:
- A new container from your custom image,
my-python-app
, is created. - Port 5000 on your machine is mapped to port 5000 in the container (
-p 5000:5000
). - The
CMD ["python", "
app.py"] is run and executes the app. - The container runs in the background because of the
-d
option (detached mode).
At this point, you can visit http://localhost:5000
in your browser, and you’ll see something like the following, which means your application is running:
If you're working in machine learning, these top Docker images for ML and AI can speed up your environment setup.
Running images with configuration
For some applications, you may need to run images with a specific configuration. Here are two common examples.
Persisting data
Containers store data temporarily. Once you delete them, the data is gone. A volume is a way to store data outside the container so it persists even if the container is removed or restarted.
To mount a volume, you need to run a command like the following:
docker run -v my-volume:/app/data my-image
The data written to /app/data
is saved in the volume even after the container is removed.
Passing environment variables
Environment variables pass configuration settings to a Docker container at runtime. This customizes your Docker containers without modifying your Docker images.
You have two ways to pass environment variables:
- You can pass environment variables using
-e
parameter. Here’s an example command:
docker run -e ENV=production -e DEBUG=False my-image
- You can create a
.env
file with all environment variables and pass it to the command. Here’s an example:
docker run --env-file .env my-image
Sample .env
file:
ENV=staging
DEBUG=True
SECRET_KEY=mysecret
Managing Running Containers
Once a container is running, you can view, stop, and access it. Let’s see how to do this.
Viewing active containers
To list all active Docker containers running on your system, execute the docker ps
command or docker container ls
. This command displays the container ID, image, command, port, status, and other details.
docker ps
# or
docker container ls
To include all containers — not just the running ones — such as those that exited or were created but not started, use the -a
flag:
docker ps -a
To view only the most recently created container, use the -l
(last) flag:
docker ps -l
If you want to see all containers sorted by creation time, with the most recent listed first, run:
docker ps -a --sort=created
Stopping and removing containers
To stop a specific running container, use the docker stop
command followed by the container ID or name:
docker stop <container_id_or_name>
To stop all running containers, use:
docker stop $(docker ps -q)
$(docker ps -q)
returns a list of all running container IDs.
Once a container is stopped, you can remove it using:
docker rm <container_id_or_name>
To remove all stopped containers, run:
docker container prune
To go further and remove unused containers, volumes, networks, and images, check out the Docker prune guide.
Accessing container logs and shell
- docker logs - The
docker logs
command batch-retrieves logs present at execution time. - docker exec -
docker exec
lets you run a new command inside an existing running container without stopping or restarting it. Think of it like opening a new terminal inside your container — so you can poke around, run scripts, check logs, or debug. - docker attach -
docker attach
connects your terminal directly to a running container’s main process. This means you can see the container’s live output (logs, prompts, etc.) and even interact with it if the process accepts input.
Troubleshooting Common Issues
Simple solutions to common problems. Here are some common errors during running Docker images and how you can approach them.
Error 1: “Error response from daemon: pull access denied for alpine-python, repository does not exist or may require ‘docker login’: denied: requested access to the resource is denied.”
- What it means: Docker tried to pull an image, in this case the
alpine-python
image from Docker Hub, but the image either doesn’t exist or is private, and you’re not authenticated. - How to fix:
- Double-check the image name and tag on Docker Hub.
- If it’s a private image, run
docker login
to authenticate. - Make sure the image exists if you're pulling from a custom registry.
Error 2: “No such image found: <image-name>:<tag>”
- What it means: You attempted to run or tag an image locally, but the image (or the specified tag) isn’t available on your system.
- How to fix:
- Use
docker images
to check available images. - Pull the image explicitly:
- Use
docker pull <image-name>:<tag>
Error 3: “manifest for <image>:<tag> not found: manifest unknown: The named manifest is not known to the registry.”
- What it means: This error likely occurs when the specified image or tag doesn’t exist.
- Possible fixes: These tips should fix most of the common errors:
- Verify the correct image and tag name.
- Refer to the image's tags on Docker Hub or your custom registry.
- Use
docker pull <image>:<tag>
to fetch a valid version. - If building locally, use a correct
Dockerfile
and build the image with:
docker build -t <image>:<tag> .
Port conflicts and bind failures
Port conflicts occur when multiple containers or a container and another application attempt to access the same port.
- How to fix:
- Use a different host port when running your container:
docker run -p 8081:80 <image>
- Stop the service currently using the port.
- Identify what’s using a port (e.g., 8080) with:
lsof -i :8080
Conclusion
Running a Docker image is one of the most important and empowering steps in using containers, whether you're spinning up a simple web server or deploying a complex application. With just a few commands like docker run
, docker ps
, and docker stop
, you're now equipped to launch, manage, and troubleshoot containers confidently.
If you're ready to go further, try building your own image with a Dockerfile, explore advanced docker run
flags, or learn how to manage multiple containers with Docker Compose.
Check out these courses to continue your Docker journey:
- Intermediate Docker: Learn advanced image management, volumes, and multi-container applications.
- Containerization and Virtualization Concepts: Understand the theory behind containers and how they differ from virtual machines.
- Containerization and Virtualization with Docker and Kubernetes: A full learning track to master Docker and get started with Kubernetes.
Master Docker and Kubernetes
FAQs
Can I run multiple containers from the same Docker image?
Yes, you can run multiple containers from the same image. Each container is isolated and can have its own settings, ports, and environment variables.
How do I pass secrets or API keys securely to a Docker container?
Use the -e
flag to set environment variables or use a .env
file and --env-file
to pass secrets at runtime without hardcoding them.
How do I run a Docker image in the background?
Use the -d
flag with docker run
to start the container in detached mode, allowing the terminal to remain available for other commands.
What is the difference between docker exec and docker attach?
docker exec
opens a new shell session inside the container, while docker attach
connects to the container’s main process and its live output.
Why do I get 'pull access denied' when running an image?
This usually means the image is private or misspelled. Check the name, tag, and ensure you're logged into Docker Hub with docker login
.
How do I persist data in a container after it stops?
Use the -v
flag to mount a volume, ensuring data is stored outside the container and remains intact even after the container is removed.
What’s the best way to run a container for development purposes?
Use the -it
flags for interactive mode, along with volume mounting and environment variables to simulate a local development environment.
How can I find out which ports are conflicting on my machine?
Use lsof -i :<port>
to identify which process is using a specific port, and then either stop it or use a different host port for your container.
How can I view logs from a running Docker container?
Use the docker logs <container_id>
command to retrieve and review logs from the container's standard output and error streams.
Srujana is a freelance tech writer with the four-year degree in Computer Science. Writing about various topics, including data science, cloud computing, development, programming, security, and many others comes naturally to her. She has a love for classic literature and exploring new destinations.