Create a container with initial resource limits
In this step, you will learn how to create a Docker container and set initial resource limits for CPU and memory. Resource limits are important for preventing a single container from consuming all available resources on the host machine, which can impact the performance of other containers and the host itself.
First, let's pull the ubuntu
image from Docker Hub. This image will be used as the base for our container.
docker pull ubuntu:latest
You should see output indicating that the image is being pulled and extracted.
Now, let's create a container named my-limited-container
with specific resource limits. We will use the docker run
command with the --cpus
and --memory
flags.
The --cpus
flag limits the amount of CPU resources the container can use. The value is a floating-point number representing the number of CPU cores. For example, --cpus 0.5
means the container can use at most half of a CPU core.
The --memory
flag limits the amount of memory the container can use. The value can be specified in bytes, kilobytes (k), megabytes (m), or gigabytes (g). For example, --memory 512m
limits the container to 512 megabytes of memory.
In this example, we will create a container that runs the sleep infinity
command, which keeps the container running indefinitely. We will limit its CPU usage to 0.5 cores and memory to 256 megabytes.
docker run -d --name my-limited-container --cpus 0.5 --memory 256m ubuntu:latest sleep infinity
Let's break down the command:
docker run
: This command is used to create and start a new container.
-d
: This flag runs the container in detached mode, meaning it runs in the background.
--name my-limited-container
: This assigns the name my-limited-container
to the container.
--cpus 0.5
: This limits the container's CPU usage to 0.5 cores.
--memory 256m
: This limits the container's memory usage to 256 megabytes.
ubuntu:latest
: This specifies the Docker image to use (the latest version of Ubuntu).
sleep infinity
: This is the command that will be executed inside the container. It keeps the container running.
After running the command, Docker will output the container ID.
To verify that the container is running and the resource limits are applied, you can use the docker inspect
command. This command provides detailed information about a container.
docker inspect my-limited-container
The output of docker inspect
is a large JSON object. You can look for the CpuShares
and Memory
fields within the HostConfig
section to see the applied limits. Note that --cpus 0.5
is translated to CpuShares
value of 512 (by default, 1 CPU is 1024 shares). The Memory
value will be in bytes.