The Wayback Machine - https://web.archive.org/web/20240904181213/https://www.geeksforgeeks.org/docker-run-command/
Open In App

Docker Run Command | Complete Tutorial

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Docker launches the containers in seconds, and the heart of running containerized applications lies in the powerful command known as ‘docker run‘. Docker is the Container Platform tool. It helps in packaging an application with all its dependencies into a single entity, and it supports running the applications as containerized images on any platform that supports Docker. It acts as a gateway for deploying and managing the Docker containers.

What Is Docker Run Command?

The `docker run` is used to create a running container from using a docker image. It is used with options, docker images, commands, and arguments. It is used for developing, shipping, and running applications in containers. With “docker run,” users can specify various options and parameters to customize the container’s behavior, such as port mappings, volume mounts, environment variables, and more.

Checking Docker Service Status

Before trying the Docker commands, ensure that the Docker software is set and the service is active. Check the status of the docker service as shown in the below the figure:

Checking status of Docker

  • If the status of the Docker service isn’t in active mode then try running the given below commands, it will enable the docker and keep it active whenever the OS is restarted.
systemctl enable docker --now

Docker Container Run

If you come to deal with the core part of the docker i.e., `docker run` is the command that is used for starting the containers with the help of assigning docker images. The minimum parameter needed with the docker run command is the docker image but the docker run command offers more options for customizing container behavior compared to other commands.

How To Use Docker Container Run Command?

Docker launches the containers by docker run command. While launching a container you can provide the extra functionalities to the container on using docker run options. The basic syntax of the docker run command is as follows:

Syntax

docker container run [OPTIONS] IMAGE [COMMAND] [ARG...]

Description

The execution of docker run command makes a api call to backend that pull the specified container image if needed for the container and then starts creating a container.

docker run [OPTIONS] IMAGE [COMMAND] [ARG…]

Command

Usage

OPTIONS

Optional flags are used for configuring the settings in container

IMAGE

A bundle of software, packages, libraries used to create docker container

COMMAND

To run/perform operations inside the container we use commands.

ARG

It is known as arguments .These are used for passing to commands for performing operations inside the container.

  • As shown in the figure below you can use the help option to know other command with the docker run.

Docker-run-help

Key Options For Docker Run Command

The following are the key options for docker run command:

Options

Usage

-d or
–detach

It is used for running container in the background mode by freeing up the terminal of the specified docker container.

–name

It is used for assigning name to the container for easy identification of particular docker container.

-p or

–publish

It is helpful in mapping the ports between the containers and the host system. This concept also called as port binding.

-v or
–volume

It is used for providing persistent volume by mounting the host directory to container file system .This concept known as volume binding.

–env

To set up environment variables inside the container. These optional flags are known as environmental variables used for providing information to inside the container.

–env-file

It options helps in reading the file of environmental variables

–cpus

used for specifying number of cpus

–help

prints docker run usage

Examples Of Docker Run Command

The docker run command can be used with many options making the container customizable with robust features. On continution of this article, we will dive on discussing the creation of container with docker run command effectively with cover all the possible options.

Docker Run To Run Docker Containers: Discover How To Do It In A Simple Way

Docker run command launches the containers with light weighted software and packages containing component known as Docker Image.On providing the optional parameters you addon the functionalities. Firstly lets see running a container in docker without using any options. The command looks as follows with using hello-world as sample image.

docker run hello-world

docker-hello_world

Run A Container Under A Specific Name

When we create a container with docker by default it provides a unique name to the creating container and it also provide the specify the name of the container by ourself with the option –name.

docker run  --name [ container_name ]  [docker _image]
  • For example considering the container_name and docker images as mycontainer, ubuntu the command will look like this:
docker run --name mycontainer centos:latest

Container-Under-specific-name

Running A Container In Detached Mode (-d)

The `-d` option is particularly useful for running the containers in the background. This is essentials for the long-running process or services that should be continued running independently of the terminal.

  • The command for running a container With Detached Mode in the background is:
docker container run -d [docker_image]

Example

docker container run -d --name myserver httpd:latest
  • The following screenshot clearly make you understand successful running of container in background without any interaction display created container.

Detach-Mode

Run A Container Interactively (-it)

When you are looking to perform operations, tasks after creating a container then you enable interactive mode while running a container. The docker provides this with options (-i) for interactive mode and (-t) for accessing the terminal. The command looks as follows:

docker container run -it [docker_image]

mydocker interactive container

Run A Container And Publish Container Ports (-p)

Docker provides an isolated network environments to the containers because of this accessing the containers from outside is not possible by default. They can only accessible from inside the containers. To provide the access from the external environment docker provides port mapping concept with option (-p). On using this option you can map the docker port with the host port. The following command shows the mapping of ports while running a container.

docker container run -p [host_port]:[container_port] [docker_image]
  • Specifying with example the command looks as follows:
docker container run -p 8080:80 [docker_image]

docker-port

Run A Container And Mount Host Volumes (-V)

In Docker, The containers containing is temporary the data will available till the container is alive (not terminated). Once the container get terminated the data inside the container will be lost and can’t be retrivable. To prevent this docker facilitates volume mounting with option (-v).

It mounts the container directory with host directory and maintainces the data over. It helps in preventing data loss and making the data permanent. The command looks as follows:

docker run -v [host_directory]:[container_directory] [docker_image]

Example For Docker Run Volume Mount

  • After specify the directories as an example the command looks as follows:
docker run -dit  -v /mydata:/tmp ubuntu:latest

docker run - volume mount

Run A Docker Container And Remove It Once the Process Is Complete

When a container executes its tasks, after completion of those it stops but the file system of the container remains on the host system. If you want to remove the container after once the container process is completed, you can use the option `–rm` provided by docker. The command looks as follows:

docker run --rm [docker_image]
  • After specify this command as an example, it looks as follows:
docker run --rm ubuntu:latest

run-and-remove-the-container

Example For Docker Run Command With Parameters

  • On specifying the values as an example to the Above docker run command with parameters the command looks as follows:
docker run -it -v /mydata:/tmp -p 8080:80 -e myuser=rajini ubuntu:latest

run-and-remove-the-container-(1)

The docker ps Command

After running the containers with docker run command, you view the launched containers with docker ps command. It list out all the running containers. If you want to see all the containers either it is running or terminated you can use (-a) option. The command looks as follows:

docker ps -a

Docker run Parameters

Till here we have understand and learn how to launch containers and to run containers with more functionality with docker run options/parameters. Now lets look on a few docker run parameters in detail. Running the containers with usage of options, facilitates better functionalities to the containers.

Foreground/Interactive (-it)

The option will be help to provide an interactive mode to the container after launching the docker container. This combinational options provides an interactive terminal for the launched container with docker run. The example looks as follows:

docker run -it alpine:latest

Clean up (–rm)

The clean up functionality helps in removing the container after once its process is done, It helps in removing the unnecessary containers and making resources available to other containers. The example of this looks as follows:

docker run --rm apline echo "hello World"

EXPOSE (Incoming Ports)

Docker Network makes the containers as isolated environments it restrict the incoming traffic from outside. But it is able to excess the outside network. For having access to incoming traffic you have to docker providing Expose option (-p) to expose particular service on that port number. The example looks as follows:

docker run -p 8080:80 ubuntu:latest

Volume Shared Filesystems (-v)

The `-v` option is used for managing the data through enabling the volume mounting. It allows the container to access the specific directories on the host system. It ensures the container data being persistent beyond the container’s lifecycle. Through mounting even if the container restarted the data will be available to access. The option looks as follows:

docker run -v [Host_directory]:[Container_directory]  [docker_image]

ENV Environment Variables (-e)

Using the `–env` or `-e` option, you can pass environment variables to the container, influencing its behavior and configuration. For a container database images such as MySQL , maridb etc.. you need to provide this environmental variables to make the containers to running state. The command looks as follows:

docker run -e MYSQL_PASSWORD=geeksforgeeks -e MYSQL_DATABASE=mydb mysql:latest 

Assigning Name( –name) , Port Number (-p) And Volume Mount (-v) Options

In this Example, I created a container with docker run with options such as detach mode (-d ) , Interactive mode ( -i ) , Terminal mode ( -t ) , ( -v ) Volume binding with host path /mydata and /var/www/html path , ( -p ) port binding with 80 port of container with 80 port of the host system and launched with image httpd on latest version. you can see the status of the container from the command `docker ps` . i.e., on looking the created, status, port columns in the result of `docker ps` command . Now you can know the age of the container , its current status duration and port that where apache is running.

docker run -dit -p 80:80 -v /mydata:/var/www/html --name myapache:latest

docker-run-apache-example

Mount Volume Read Only (–read-only)

On using volumes in combination with the –read-only flag helps in controlling the writing permissions of a file. The following command illustrates it clearly as the read-only flag mounted to container’s root filesystem allowing only to read and prohibiting the write permissions to location other other than the specified volumes for the container.

docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v /path/to/static-docker-binary:/usr/bin/docker busybox sh

Publish All Exposed Ports (-P, –publish-all)

It lets to publish all the exposed ports of a container to the host. Docker binds each exposed port to a random port number available in the host system.

docker run -P nginx:alpine

An Implementation Of Docker Run: A Step-By-Step Guide

In this implementation we will guide you how to create images and create containers in simple and effectively. You can simple think that Docker run execution is a combination of docker container create and container start. Lets discuss the implementation about the execution of this example and how it’s workflow will be.

Example

docker run -it --name mycontainer1 ubuntu:latest bash 

Step 1: Check If The Image Exists Locally

Firstly it checks the images that are available in the local docker system using the following command in behind:

docker images

If the required ubuntu:latest looking is exists then it go for creating the container as next step or else, the docker images has to be pulled into local system from the public registry or have to provide own custom Image.

Step 2: Create A New Container From The Image

Once the docker image availability verfied it will starts to create the container with that image, for this it uses docker create command in behind for creating the container and names with mycontainer by taking through option –name.

Through this creation phase of container some resources such as hostname, CPU, memory and storage. The container is created with some namespace. It provides the isolated network environment to the container.

Step 3: Start The Container And Run The Container

Once the docker container is started, then as a next phase docker start the container, for this It uses docker start command to start the container. After the docker container is started it uses the enterpoint or command to run a specified program inside it.

Step 4: Attach To The Containe And Print Out The Output To The Console

Now, As final phase of the docker run command it will run the bash program that is specified in the command using the entrypoint, Here you will be landed to the terminal with interactive mode, and can see the bash program in running state.

  • You can check all these stages will executing the initial specfied example command
docker run -it --name mycontainer1 ubuntu:latest bash 

Creating a Container

Running Interactive vs Detached Containers

The following are the difference between running interactive vs Detached Containers:

Aspect Interactive Mode (-it flag) Detached Mode (-d flag)
Interaction Real-time interaction with the container Runs in the background, terminal remains free
Ideal For Development, debugging, short-term tasks Production services, background applications
Control Direct control via terminal Managed via Docker commands (e.g., docker logs)
Use Cases Debugging, command execution Long-term services, daemons

Best Practices of Docker Run Command

The following are the best practices of docker run command:

  • Resource Management: Limit CPU and memory usage with --cpus and --memory flags to prevent resource contention.
  • Networking: Use the --network flag to specify custom networks for better container communication and security.
  • Volumes: Utilize the -v flag to mount volumes, ensuring data persistence and isolation from the container lifecycle.
  • Security: Run containers with the least privileges necessary by using the --user flag and avoiding the root user.

Common Usecases of Docker Run

The following are the usecases of Docker Run Command:

  • Running Applications: It facilitates with quickly start the applications in isolated environments using specific images.
  • Development and Testing: It helps in creating consistent development environments and run tests in containers.
  • Microservices Deployment: It is useful in deploying and managing the microservices architecture efficiently.
  • Continuous Integration/Continuous Deployment (CI/CD): It helps streamlining the application automation of build, test, and deployment processes.

People Also Read

Article Name

Article Link

Docker Installation on Linux distributions

Read

Docker Installation on Windows

Read

Docker Installation on Linux MacOS

Read

Conclusion

In conclusion, mastering the `docker run` command is crucial for effective deployment and managing Docker containers. Whether you are launching applications, services, or development environments, understanding the multitude of options available with `docker run`. It will devlops you to support to your containers to specific requirements. Experimentation with the various flags and options will make better understanding on the container workflow in launching the applications or deployments . To know more about other docker commands try on referring Docker Cheat Sheet.

Docker Run Command – FAQs

In Docker, What Is The Primary Purpose Of `docker run` ?

`docker run` is used to create and start a docker container with the specified image facilitating the execution of containerized applications.

How To Run A Docker Container In Background ?

Add the ‘-d’ flag to the ‘docker run’ command to run the docker container in background, executing independent of the terminal .

What Are ‘-p’ And ‘-v’ Options In The Docker ?

These are known as port binding and volume binding options that are used with docker run , to map the port numbers and path directories of docker container with the host system.

Example of Port Binding:

docker run -p 80:80  -v /mydata:/var/www/html --name myserver httpd:latest

Can I Change The Values Of Environmental Variables Inside The Docker Container?

Yes , you can set the evironmental variables from the ‘docker run‘ command and those can be changable inside the container from the bash shell .

Can We Create A Container Without Docker Run Command ?

Yes , we can create by using following commands , Firstly run

`docker create --name container_name    image_name`

(or)

`docker container create --name container_name    image_name`

and then run the

`docker start  container_name`

What Is Docker Run Image?

Running a container with docker run command using docker image (A light weight Software) is known as Docker Run Image. The command looks as follows:

docker run [docker_image]

What Is Docker Port Mapping?

Mapping of docker port with its host ports to provide the access to the containers with docker environments is known as Docker Port Mapping.

What Are Docker Run Name?

Providing the name to the container at time of launching is known docker run name. The command looks as follows:

docker run --name mycontainer -dit ubuntu:latest



Similar Reads

Docker Tips : about /var/run/docker.sock
Docker has thus gained lots of usage today in software development. It allows developers to create, deploy, and run their applications in isolated environments. Such isolation will guarantee consistency between development, testing, and production environments and, finally, app security and scalability. A central part of the functionalities of Dock
8 min read
Docker Start vs Docker Run
Docker is a platform as a service(PaaS) that allows engineers to use OS-level virtualization to automate the deployment of applications inside lightweight and portable packages called containers. The containers have a very big advantage as they allow apps to run on different platforms effortlessly, and reduce the old headache of "it runs on my mach
7 min read
How to See RUN Command Output in Docker BuildKit
Docker build is one of the most crucial parts of the operation of containerizing applications. Docker's traditional build system has served developers well, but with projects growing in complexity, the need for better builds that are more efficient and flexible was well apparent. Enter BuildKit, the next-generation build architecture for Docker, ai
6 min read
Run PostgreSQL on Docker and Setting Up pgAdmin
PostgreSQL, an effective tool, is a free­-to-use relational database management system. Docker can quickly construct and orche­strate its instances without bothering about the complexity of setup or depe­ndencies. This step-by-step simple guide will show you how to get Postgre­SQL on Docker, and then, use the pgAdmin extension to look at the databa
7 min read
How To Run A Cron Job Inside A Docker Container ?
In the containerization world, management of resources and scaling the applications are necessary to make our services effective and user-friendly for the users. In this, the cron job helps in a significant way with facilitating features such as isolation, portability, scalability, and resource management. It will be a convenient and efficient solu
5 min read
How to Run GUI Based Applications inside Docker?
A Docker Container is an isolated application platform that contains everything needed to run an application built from one or more images. Docker is an Open Source project that provides an open platform to run any number of applications inside a container according to your requirements and you can also save that environment for future use also as
7 min read
Docker Compose Tool To Run aMulti Container Applications
The article talks about how to run multi-container applications using a single command. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you can configure a file (YAML file) to configure your docker containers. Then Once you configured the Yaml file with a single command, you create and start all
8 min read
Difference between RUN vs CMD vs ENTRYPOINT Docker Commands
Understanding the distinctions between the RUN, CMD, and ENTRYPOINT commands in Docker is essential for optimizing your containerized applications. Each of these commands serves a unique purpose in Dockerfile instructions, impacting how containers are built and executed. In this article, we will delve into the specifics of RUN, CMD, and ENTRYPOINT,
3 min read
How to start or run docker daemon
Docker has had a significant impact on the development, shipping, and deployment of applications. By using containerization, Docker allows a developer to package an application along with all the dependencies into standard units termed containers. This way, it makes sure the application behaves uniformly across any environment, starting from develo
6 min read
Docker Run with Environment Variables
Containerization has significantly advanced software development by packaging applications and their dependencies together and containerizing them to ensure consistency across multiple environments. Environment variables are one of the most important features of containerization as they make it possible to manage configuration and behavior. Imagine
7 min read
How to Run a Python Script using Docker?
Docker helps you to run your python application very smoothly in different environments with out worrying about underlying platforms. Once you build an image using dockerfile you can run that image where ever you want to run. Docker image will help you to package all the dependencies required for the application which will used for further while ru
6 min read
How to Use Docker For Fault Tolerance with Docker Replicas?
Docker is a set of platform-as-a-service products that use OS-level virtualization to deliver software in packages called containers. A cluster of docker engines is called a swarm. Docker Swarm is a cluster management and orchestration feature embedded in the Docker Engine. Docker ReplicasDocker replicas refer to running multiple instances of a doc
4 min read
How to Use Docker For Cross-Platform Containerization with Docker Buildx?
Docker has completely modified the manner in which software program is evolved and deployed, with the aid of introducing containerization generation. In order to package programs with their dependencies and make certain consistency of conduct across many contexts, packing containers offer a compact and portable solution. Deploying containerized app
7 min read
How to Use Docker Content Trust to Verify Docker Container Images
The world of containerized applications is based on trust. You rely on Docker images to be exactly what they say they are: secure, reliable, robust, and built with the right elements. But just like you can not just blindly trust any random ingredient in your kitchen, similarly the Docker image needs a kind of verification so we don't need to be con
12 min read
Docker Compose vs Docker Swarm
Docker is one of the most widely used container-based software on the market. Docker is an open-source platform for creating, deploying, and managing containerized applications. Docker allows us to simply bundle our apps into containers and can be deployable on any platform that supports docker software acting as a platform independent. What Is Doc
6 min read
Docker CLI vs Docker Desktop
Docker is an open-source platform. It is used to containerize applications. This is done by packaging applications along with their dependencies into containers that can be easily deployed. Users interact with Docker primarily using either the Docker CLI or the Docker Desktop Application. In this article, we'll be looking into each one in detail an
5 min read
Docker: How To Use Bash With An Alpine Based Docker Image?
Docker is a tool that is used to encapsulate the application with all its dependencies, called Docker containers. On the other hand, Alpine Linux is a lightweight and minimal Linux distribution. Here in this guide, I will first discuss what Docker is. Then I will discuss what Alpine is. After this, I will walk you through the different steps to ins
5 min read
Docker - Deploying WebApps on Docker
Docker applies abstraction at the software layer of the operating system to create an instant and portable environment that includes everything you need: a Linux kernel, libraries, system tools like grep or sshfs, plus applications (web servers/services) and all dependencies needed by those applications (e.g., database engines). When deployed, thes
9 min read
How To Use Docker Security Tools To Secure Docker Container Images
Docker is a tool that is used to package the application and its dependencies into compact units called Docker containers. In this guide, I will first discuss what a docker is. Then I will discuss a security tool called Trivy, which is used to scan and detect Docker image vulnerabilities. After this, I will walk you through the different steps to d
11 min read
Docker - Publishing Images to Docker Hub
Docker is a container platform that facilitates creating and managing containers. In this article, we will see how docker stores the docker images in some popular registries like Dockerhub and how to publish the Docker images to Docker Hub. By publishing the images to the docker hub and making it public it gives users more flexibility in creating e
8 min read
Docker - Using Public Repositories To Host Docker Images
Docker is a software platform for creating isolated virtualized environments for building, deploying, and testing applications with ease. In this tutorial, we will learn how to host public repositories on docker hub which is a hosted repository service provided by Docker for finding and sharing container images. Just like GitHub allows the hosting
10 min read
Docker - Docker Container for Node.js
Node.js is an open-source, asynchronous event-driven JavaScript runtime that is used to run JavaScript applications. It is widely used for traditional websites and as API servers. At the same time, a Docker container is an isolated, deployable unit that packages an application along with its dependencies, making it highly scalable and maintainable.
12 min read
Getting started with Spring Boot 3, Kafka over docker with docker-compose.yaml
We will create two Spring Boot 3.x applications (Producer and Consumer) requiring Java 17 to get started. We need a queuing service to pass messages from the producer Spring service to the consumer Spring service. Here, we will use Kafka. Confluent provides Docker images that are easy to use for setting up the Kafka environment. Since we will use a
5 min read
Docker Logs Inside the Docker Container
While running containers, it is important to know about various information like running processes generated by the container. Docker logs allow us to get this information regarding the containers. While it's pretty straighforward to check logs directly from Docker CLI, here we will see how to check logs from within a container. What is Docker?Dock
5 min read
How To Use Docker Desktop To Deploy Docker Containerized Applications
Docker Desktop is an user-friendly tool that simplifies the deployment of Docker containerized applications on your local machine. It provides a graphical interface for managing containers, images, and volumes, making it accessible for developers and DevOps professionals. In this guide, we will walk you through the essential steps of using Docker D
9 min read
How to Run curl Command From Within a Kubernetes Pod?
Ever needed to fetch data or test connectivity from within a Kubernetes pod? The curl command becomes your trusty companion in these situations. This guide explores different approaches to execute curl commands directly from within your Kubernetes pod, empowering you to diagnose issues and interact with external services effectively. What are Kuber
3 min read
What Is Docker rm Command ?
"docker rm" is used to remove one or more Docker containers that are running on the Docker host. A Docker container uses up system resources like CPU, memory, and disk space when it is running. To free up such resources, you may choose to uninstall a container after using it for a while. docker rm [OPTIONS] CONTAINER [CONTAINER...] OPTIONS: Various
3 min read
What is Docker PS Command ?
he "docker ps" command is used to list all the running containers in the docker host. With the help of some filters, you can get the output of all the containers in the docker with are running and that are stopped. it shows the list of active containers that includes details about each one, including its name, ID, creation image, program being run
5 min read
How do I Download Docker Images Without Using the Pull Command?
Nowadays, effective packaging and deployment are closely associated with Docker in the world of containerized apps. A common Docker task is pulling images from registries, which can be completed with the all-purpose docker pull command. However, you do not have to use this command-line interface to retrieve Docker images; there are other alternativ
5 min read
How to Install ""ifconfig"" Command in My Ubuntu Docker Image?
Docker images are templates that include all the code, libraries, dependencies, and runtime required to run an application. They guarantee consistency and portability across several systems, which makes them indispensable in containerized contexts. Docker images make it simple to scale, deploy, and manage applications, which promotes quicker develo
6 min read