top of page

Why should you use the --memory argument in Docker container?

Docker Memory

In Docker, you can use the --memory argument with the container run child command to define a hard memory restriction. After establishing this limit, Docker does not allow a container to utilise more than a specified amount of user or system RAM.

Why Setting Memory Limits Is Important?

  • Resource Efficiency: By defining memory constraints, you ensure that containers do not consume more resources than necessary, preventing resource contention with other applications running on the host system.

  • Predictable Performance: Memory limits help maintain consistent performance for both the containerized application and other processes on the host machine. Predictable performance is essential for reliable application behaviour.

  • Preventing Out-of-Memory(OOM) Issues: Without memory limits, a container can potentially use all available system memory, leading to out-of-memory issues and potential crashes. Setting limits helps avoid such scenarios.

Set Memory Limit Setting:

To set a memory limit for a Docker container, use the --memory option when running the container. Here's a basic example:

[root@siddhesh ~]# docker run -dt -p 443:80 --memory=2G nginx
[root@siddhesh ~]#

In this command, --memory=2G sets the memory limit to 2 GB. Adjust the value based on your application's requirements and the available resources on your host machine.

[root@siddhesh ~]# docker inspect bd39c9deb592055b494dcdfbbbd80128e7828bb94c9873282fcd4380826baa30|grep -i "Memory"|head -n 1
            "Memory": 2147483648,
[root@siddhesh ~]#

This value represents the memory limit for the container. The value is given in bytes. In this case, the memory limit for the container is 2147483648 bytes, which is equivalent to 2 gigabytes (GB).

Set SWAP Memory Limit Setting:

While setting the memory limit is essential, it's also possible to restrict the container's swap space using the --memory-swap option. The swap limit is the total memory plus swap, so it's an upper limit on the container's memory usage.

[root@siddhesh ~]# docker run -dt -p 443:80 --memory=2G --memory-swap=4G nginx
[root@siddhesh ~]#

In this example, the --memory option is set to 2 gigabytes, and the --memory-swap option is set to 4 gigabytes.

[root@siddhesh ~]# docker inspect bd39c9deb592055b494dcdfbbbd80128e7828bb94c9873282fcd4380826baa30|egrep -i "Memory|MemorySwap"
            "Memory": 2147483648,
            "MemorySwap": 4294967296,
[root@siddhesh ~]#

The value is given in bytes. In this case, the total memory limit (including swap) for the container is 4294967296 bytes, which is equivalent to 4 gigabytes (GB). The memory swap space is used when the container exceeds its allocated memory limit.

bottom of page