Docker Run Command Parameters

DockerDockerBeginner
Practice Now

Introduction

In this lab, we will focus exclusively on the docker run command and its various parameters. The docker run command is fundamental to Docker operations, allowing us to create and start containers with specific configurations.

By mastering the parameters of this command, you'll gain greater control over your containerized applications, enhancing your ability to deploy and manage Docker containers effectively.

We'll cover a wide range of parameters including those for naming, detached mode, port mapping, volume mounting, environment variables, resource constraints, and more.

Some of the parameters you may already be familiar with, while others might be new to you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL docker(("`Docker`")) -.-> docker/ContainerOperationsGroup(["`Container Operations`"]) docker(("`Docker`")) -.-> docker/NetworkOperationsGroup(["`Network Operations`"]) docker(("`Docker`")) -.-> docker/VolumeOperationsGroup(["`Volume Operations`"]) docker/ContainerOperationsGroup -.-> docker/exec("`Execute Command in Container`") docker/ContainerOperationsGroup -.-> docker/port("`List Container Ports`") docker/ContainerOperationsGroup -.-> docker/run("`Run a Container`") docker/ContainerOperationsGroup -.-> docker/inspect("`Inspect Container`") docker/NetworkOperationsGroup -.-> docker/network("`Manage Networks`") docker/VolumeOperationsGroup -.-> docker/volume("`Manage Volumes`") docker/ContainerOperationsGroup -.-> docker/ls("`List Containers`") subgraph Lab Skills docker/exec -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/port -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/run -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/inspect -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/network -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/volume -.-> lab-389228{{"`Docker Run Command Parameters`"}} docker/ls -.-> lab-389228{{"`Docker Run Command Parameters`"}} end

Basic Docker Run and Container Naming

Let's start with the basics of docker run and explore how to name our containers.

First, run a basic Nginx container:

docker run nginx

This command runs an Nginx container in the foreground. You'll see a stream of log output in your terminal. This is because the container is running in the foreground, and it's showing you the logs directly.

To stop this container, press Ctrl+C. You might notice it takes a few seconds to stop - this is normal, as Docker is giving the container time to shut down gracefully.

Now, let's run it in detached mode and give it a name:

docker run -d --name my-nginx nginx

Let's break down this command:

  • docker run: This is the basic command to run a container.
  • -d: This option runs the container in detached mode, meaning it runs in the background. You won't see any output in your terminal.
  • --name my-nginx: This assigns the name "my-nginx" to the container. If you don't specify a name, Docker will assign a random name.
  • nginx: This is the name of the image we're using to create the container.

After running this command, you'll see a long string of characters. This is the container ID. Docker has started the container in the background.

If you encounter an error saying the name is already in use, it means you have a container with that name already. You can either choose a different name or remove the existing container (we'll learn how to do this in later labs).

Port Mapping

The -p parameter in docker run allows us to map ports from the container to the host. This is crucial for accessing services running inside the container from your host machine.

Run an Nginx container with port mapping:

docker run -d --name nginx-mapped -p 8080:80 nginx

Let's break down the new parts of this command:

  • -p 8080:80: This maps port 8080 on your host to port 80 in the container. The format is always host_port:container_port.

Nginx, by default, runs on port 80 inside the container. By mapping it to port 8080 on our host, we can access it by going to localhost:8080 in a web browser.

Now, let's verify the Nginx welcome page is accessible. We'll use the curl command, which allows us to make HTTP requests from the command line:

curl http://localhost:8080

You should see the HTML content of the Nginx welcome page. If you don't have curl installed, you can install it with:

sudo apt-get update && sudo apt-get install -y curl

If you still can't access the page, here are a few things to check:

  1. Make sure the container is running: docker ps | grep nginx-mapped
  2. Check if the port is actually mapped: docker port nginx-mapped
  3. If you're using a cloud server, make sure the firewall allows traffic on port 8080.

Volume Mounting

The -v parameter in docker run allows us to mount volumes, sharing data between the host and the container. This is incredibly useful for persisting data or for providing configuration files to the container.

Let's start by creating a simple directory structure on our host:

mkdir -p ~/project/nginx-data
echo "<html><body><h1>Hello from mounted volume</h1></body></html>" > ~/project/nginx-data/index.html

These commands do the following:

  1. Create a new directory nginx-data inside the project folder in your home directory.
  2. Create a simple HTML file named index.html inside this new directory.

Now, let's run an Nginx container and mount this directory:

docker run -d --name nginx-volume -p 8081:80 -v ~/project/nginx-data:/usr/share/nginx/html nginx

Let's break down this command:

  • docker run: This is the command to run a new container.
  • -d: This runs the container in detached mode (in the background).
  • --name nginx-volume: This assigns the name "nginx-volume" to our container.
  • -p 8081:80: This maps port 8081 on the host to port 80 in the container.
  • -v ~/project/nginx-data:/usr/share/nginx/html: This mounts the nginx-data directory from our host to the /usr/share/nginx/html directory in the container. This is where Nginx looks for content to serve.
  • nginx: This is the name of the image we're using to create the container.

Now, let's verify that the custom page is being served:

curl http://localhost:8081

You should see the content of your custom HTML file: "Hello from mounted volume!"

If you don't see your custom content, here are a few things to check:

  1. Make sure the ~/project/nginx-data/index.html file exists on your host system.
  2. Check that the container is running: docker ps | grep nginx-volume
  3. Check the Nginx logs for any errors: docker logs nginx-volume

This method of mounting a host directory to a container is called a bind mount. It's a straightforward way to share files between the host and the container. Here are a few key points to remember:

  1. The host directory path must be an absolute path.
  2. If the host directory doesn't exist, Docker will create it automatically.
  3. Any changes made to files in this directory (either on the host or in the container) will be immediately visible to both the host and the container.
  4. Be careful with permissions: the container runs as root by default, which might create files that your host user can't modify.

By using this method, we avoid the "not a directory" error because we're mounting a directory, not a single file. This approach gives you more flexibility to add, remove, or modify files without having to recreate the container.

Environment Variables

The -e parameter in docker run allows us to set environment variables in the container. This is useful for configuring the application running in the container without changing its code.

Run a container with environment variables:

docker run -d --name nginx-env -e NGINX_HOST=mywebsite.com -e NGINX_PORT=80 nginx

Let's break down the new parts:

  • -e NGINX_HOST=mywebsite.com: This sets an environment variable named NGINX_HOST with the value mywebsite.com.
  • -e NGINX_PORT=80: This sets another environment variable NGINX_PORT with the value 80.

Environment variables are a key-value pair that can be accessed by processes running inside the container. Many Docker images are designed to use specific environment variables for configuration.

You can verify the environment variables:

docker exec nginx-env env | grep NGINX_

This command does the following:

  • docker exec nginx-env: This tells Docker to execute a command in the running nginx-env container.
  • env: This command prints out all environment variables.
  • | grep NGINX_: This filters the output to only show lines containing "NGINX_".

You should see your two environment variables listed.

If you don't see the environment variables, check:

  1. Is the container running? Verify with docker ps | grep nginx-env
  2. Did you spell the environment variable names correctly in your docker run command?

Resource Constraints

Docker allows you to set resource constraints on containers using various parameters in docker run. This is crucial for managing the performance and stability of your host system, especially when running multiple containers.

Run a container with memory and CPU limits:

docker run -d --name nginx-limited --memory 256m --cpus 0.5 nginx

Let's break down the new parts:

  • --memory 256m: This limits the container to 256 megabytes of memory. The 'm' stands for megabytes. You could also use 'g' for gigabytes.
  • --cpus 0.5: This limits the container to use at most half of a CPU core.

These limits prevent the container from using more resources than specified, which can help prevent a single container from monopolizing the host's resources.

You can verify these limits were applied correctly:

docker inspect -f '{{.HostConfig.Memory}}' nginx-limited
docker inspect -f '{{.HostConfig.NanoCpus}}' nginx-limited

The first command should output 268435456 (256MB in bytes), and the second should output 500000000 (0.5 CPU in nano-units).

If you see different values, double-check your docker run command to make sure you specified the limits correctly.

Note: Setting resource limits too low can cause the container to perform poorly or even crash. If you're having issues with your container, try increasing these limits.

Network Settings

The --network parameter in docker run allows you to connect a container to a network. This is useful for container-to-container communication and for isolating groups of containers.

First, create a custom bridge network:

docker network create my-custom-network

This creates a new bridge network named my-custom-network. Bridge networks are the most common network type in Docker.

Now, run a container connected to this network:

docker run -d --name nginx-networked --network my-custom-network nginx

The --network my-custom-network option connects the container to the network we just created.

Containers on the same network can communicate with each other using their container names as hostnames. This makes it easy to link services together.

If you get an error saying the network doesn't exist, make sure you've created the network correctly with the docker network create command.

Restart Policies

The --restart parameter in docker run allows you to specify a restart policy for the container. This is useful for ensuring that your containers stay running, even if they crash or if the Docker daemon restarts.

Run a container with a restart policy:

docker run -d --name nginx-restart --restart unless-stopped nginx

The --restart unless-stopped option sets the restart policy to "unless-stopped", meaning the container will restart automatically unless it is explicitly stopped by the user.

Other restart policies include:

  • no: The default. Don't automatically restart the container.
  • on-failure: Restart only if the container exits with a non-zero status.
  • always: Always restart the container regardless of the exit status.

You can verify the restart policy:

docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' nginx-restart

This should output unless-stopped.

If you don't see the expected output, double-check your docker run command to ensure you specified the restart policy correctly.

Working Directory and Command

In this step, we'll explore how to set a working directory inside a container and run custom commands when a container starts.

The -w parameter in docker run sets the working directory inside the container, and you can specify a command to run after the image name.

Let's combine these concepts:

docker run -d --name nginx-custom -w /app nginx sh -c "touch newfile.txt && nginx -g 'daemon off;'"

Let's break this command down:

  • -d: Run the container in detached mode (in the background).
  • --name nginx-custom: Name the container "nginx-custom".
  • -w /app: Set the working directory inside the container to /app.
  • nginx: The name of the image to use.
  • sh -c "...": Run a shell command.
    • touch newfile.txt: Create an empty file named newfile.txt.
    • &&: Run the next command if the previous one succeeded.
    • nginx -g 'daemon off;': Start Nginx in the foreground, keeping the container running.

Now, let's verify that the container is running and the file was created:

docker ps | grep nginx-custom
docker exec nginx-custom ls -l /app/newfile.txt

The first command should show that the container is running, and the second command should list the details of the newfile.txt file in the /app directory of the container.

Summary

In this lab, we've taken a deep dive into the docker run command, exploring its various parameters and options. We've covered:

  1. Basic container running and naming
  2. Port mapping to access container services from the host
  3. Volume mounting to share data between host and container
  4. Setting environment variables for container configuration
  5. Applying resource constraints to limit container resource usage
  6. Network settings for container communication
  7. Restart policies for container reliability
  8. Working directory and command specification for container startup

These parameters of docker run provide powerful tools for configuring and managing your Docker containers. By mastering these options, you can create more sophisticated and tailored container deployments. You can control how containers interact with the host system, what resources they can consume, and how they behave in different scenarios.

Other Docker Tutorials you may like