<p>I'm running Kubernetes 1.2.0 on a number of lab machines. The machines have swap enabled. As the machines are used for other purposes, too, I cannot disable swap globally.</p>

<p>I'm observing the following problem: If I start a pod with a memory limit, the container starts swapping after it reached the memory limit. I would expect the container to be killed.</p>

<p>According to <a href="https://github.com/kubernetes/kubernetes/issues/7294" rel="nofollow noreferrer">this issue</a> this was a problem that has been fixed, but it still occurs with Kubernetes 1.2.0. If I check the running container with <code>docker inspect</code>, then I can see that <code>MemorySwap = -1</code> and <code>MemorySwappiness = -1</code>. If I start a pod with low memory limits, it starts swapping almost immediately.</p>

<p>I had some ideas, but I couldn't figure out how to do any of these:</p>

<ul>
<li>Change the default setting in Docker so no container is allowed to swap</li>
<li>Add a parameter to the Kubernetes container config so it passes <code>--memory-swappiness=0</code></li>
<li>Fiddle with docker's cgroup and disallow swapping for the group</li>
</ul>

<p>How can I prevent the containers to start swapping?</p>

<p>Kubernetes, specifically the <code>kubelet</code>, <a href="https://github.com/kubernetes/kubernetes/commit/f4edaf2b8c32463d6485e2c12b7fd776aef948bc" rel="nofollow noreferrer">fails if swap is enabled on Linux since version <code>1.8</code> (flag <code>--fail-swap-on=true</code>)</a>, as <a href="https://github.com/kubernetes/kubernetes/issues/7294" rel="nofollow noreferrer">Kubernetes can't handle swap</a>. That means you can be sure that swap is disabled by default on Kubernetes.</p>

<p>To test it in local Docker container, <a href="https://github.com/moby/moby/issues/18894#issuecomment-167177866" rel="nofollow noreferrer">set <code>memory-swap == memory</code></a>, e.g.:</p>

<p><code>docker run --memory="10m" --memory-swap="10m" dominikk/swap-test</code></p>

<p>My test image is based on <a href="https://unix.stackexchange.com/questions/1367/how-to-test-swap-partition/1368#1368">this small program</a> with the addition to flush output in Docker:</p>

<pre class="lang-c prettyprint-override"><code>setvbuf(stdout, NULL, _IONBF, 0);  // flush stdout buffer every time
</code></pre>

<p>You can also test it with <code>docker-compose up</code> (<a href="https://docs.docker.com/compose/compose-file/compose-versioning/#version-2x-to-3x" rel="nofollow noreferrer">only works for <code>version &lt;= 2.x</code></a>):</p>

<pre class="lang-yaml prettyprint-override"><code>version: '2'
services:
  swap-test:
    image: dominikk/swap-test
    mem_limit: 10m
    # memswap_limit:
    #           -1: unlimited swap
    #            0: field unset
    #           &gt;0: mem_limit + swap
    # == mem_limit: swap disabled
    memswap_limit: 10m
</code></pre>
