One place for hosting & domains

      Como Adicionar Espaço de Swap (troca) no Ubuntu 18.04


      Justin Ellingwood escreveu uma versão anterior deste tutorial.

      Introdução

      Uma das formas mais fáceis de se proteger contra erros fora da memória em aplicativos é adicionar um pouco de espaço de swap no seu servidor. Neste guia, falaremos sobre como adicionar um arquivo swap a um servidor Ubuntu 18.04.

      Aviso: Embora o swap seja geralmente recomendado para sistemas utilizando discos rígidos tradicionais, usar o swap com SSDs pode causar problemas de degradação de hardware ao longo do tempo. Devido a essa consideração, não recomendamos a habilitação do swap no DigitalOcean ou em qualquer outro provedor que utiliza armazenamento SSD. Fazer isso pode afetar a confiabilidade do hardware subjacente para você e seus vizinhos. Este guia é fornecido como referência para usuários que possam ter sistemas de disco rígido tradicional em outro lugar.

      Se você precisa melhorar o desempenho do seu servidor na DigitalOcean, recomendamos que atualize seu Droplet. Isso resultará em melhores resultados no geral e diminuirá a probabilidade de contribuir para problemas de hardware que possam afetar seu serviço.

      O que é o Swap?

      Swap é uma área em um disco rígido que foi designada como um lugar onde o sistema operacional pode armazenar temporariamente dados que ele já não pode manter em RAM. Basicamente, isso dá a você a capacidade de aumentar a quantidade de informações que seu servidor pode manter em sua “memória” operacional, com algumas limitações. O espaço de swap no disco rígido será usado principalmente quando já não houver espaço suficiente em RAM para manter os dados do aplicativo em uso.

      As informações gravadas no disco ficarão significativamente mais lentas do que as informações mantidas em RAM, mas o sistema operacional preferirá manter os dados do aplicativo em memória e usar o swap para os dados mais antigos. De maneira geral, ter espaço de swap como uma alternativa para quando a RAM do seu sistema estiver esgotada pode ser uma boa estratégia de segurança contra exceções de memória insuficiente nos sistemas com armazenamento disponível que não seja SSD.

      Passo 1 – Verificando o Sistema em Relação às Informações de Swap (troca)

      Antes de começarmos, podemos verificar se o sistema já tem algum espaço de swap (troca) disponível. É possível ter vários arquivos de swap ou partições de swap, mas geralmente um deve ser o suficiente.

      Podemos descobrir se o sistema tem algum swap configurado digitando:

      Se você não receber nenhum resultado, isso significa que seu sistema não tem espaço de swap disponível atualmente.

      Você pode verificar se não existe um swap ativo usando o utilitário free:

      Output

      total used free shared buff/cache available Mem: 985M 84M 222M 680K 678M 721M Swap: 0B 0B 0B

      Como você pode ver na linha Swap do resultado, nenhum swap está ativo no sistema.

      Passo 2 – Verificando o Espaço Disponível na Partição do Disco Rígido

      Antes de criarmos nosso arquivo de swap, verificaremos o uso atual do disco para garantir que temos espaço suficiente. Faça isso digitando:

      Output

      Filesystem Size Used Avail Use% Mounted on udev 481M 0 481M 0% /dev tmpfs 99M 656K 98M 1% /run /dev/vda1 25G 1.4G 23G 6% / tmpfs 493M 0 493M 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 493M 0 493M 0% /sys/fs/cgroup /dev/vda15 105M 3.4M 102M 4% /boot/efi tmpfs 99M 0 99M 0% /run/user/1000

      O dispositivo com / na coluna Mounted on é o nosso disco neste caso. Temos bastante espaço disponível neste exemplo (apenas 1,4 GB usado). Seu uso provavelmente será diferente.

      Apesar da divergência de opiniões quanto ao tamanho adequado de um espaço de swap, isso realmente dependerá de suas preferências pessoais e das exigências da sua aplicação. Geralmente, um espaço igual ou duas vezes o tamanho do espaço da RAM no seu sistema é um bom ponto de partida. Outra boa regra de ouro é que qualquer coisa acima de 4 GB de swap é provavelmente desnecessária se você somente estiver usando-o como uma alternativa para a RAM.

      Passo 3 – Criando um Arquivo de Swap

      Agora que sabemos qual é o espaço disponível em nosso disco rígido, podemos criar um arquivo de swap no nosso sistema de arquivos. Alocaremos um arquivo do tamanho do swap que desejarmos chamar de swapfile no nosso diretório raiz (/).

      A melhor maneira de criar um arquivo de swap é com o programa fallocate. Este comando cria instantaneamente um arquivo do tamanho especificado.

      Uma vez que o servidor no nosso exemplo tem 1 GB de RAM, criaremos um arquivo de 1 GB neste guia. Ajuste isso para atender às necessidades do seu próprio servidor:

      • sudo fallocate -l 1G /swapfile

      Podemos verificar se a quantidade correta de espaço foi reservada digitando:

      • -rw-r--r-- 1 root root 1.0G Apr 25 11:14 /swapfile

      Nosso arquivo foi criado com a quantidade correta do espaço reservado.

      Passo 4 – Habilitando o Arquivo de Swap

      Agora que temos um arquivo do tamanho correto disponível, precisamos realmente transformar isso em espaço de swap.

      Primeiro, precisamos bloquear as permissões do arquivo para que apenas os usuários com privilégios root possam ler o conteúdo. Isso impede que os usuários normais possam acessar o arquivo, o que teria implicações de segurança significativas.

      Torne o arquivo acessível somente para root digitando:

      Verifique a alteração de permissões digitando:

      Output

      -rw------- 1 root root 1.0G Apr 25 11:14 /swapfile

      Como você pode ver, apenas o usuário root tem os sinalizadores de leitura e gravação habilitados.

      Podemos agora marcar o arquivo como espaço de swap digitando:

      Output

      Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=6e965805-2ab9-450f-aed6-577e74089dbf

      Depois de marcar o arquivo, podemos habilitar o arquivo de swap, permitindo que nosso sistema comece a usá-lo:

      Verifique se o swap está disponível digitando:

      Output

      NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -2

      Podemos verificar a saída do utilitário free novamente para corroborar nossos resultados:

      Output

      total used free shared buff/cache available Mem: 985M 84M 220M 680K 680M 722M Swap: 1.0G 0B 1.0G

      Nosso swap foi configurado com sucesso e nosso sistema operacional começará a usá-lo conforme necessário.

      Passo 5 – Tornando o Arquivo de Swap Permanente

      Nossas alterações recentes habilitaram o arquivo de swap para a sessão atual. No entanto, se reiniciarmos, o servidor não manterá as configurações de swap automaticamente. Podemos alterar isso adicionando o arquivo de swap ao nosso arquivo /etc/fstab.

      Faça um backup do arquivo /etc/fstab para o caso de algo dar errado:

      • sudo cp /etc/fstab /etc/fstab.bak

      Adicione a informação do arquivo de swap no final do seu arquivo /etc/fstab digitando:

      • echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

      Em seguida, avaliaremos algumas configurações que podemos atualizar para ajustar nosso espaço de swap.

      Passo 6 – Ajustando as Configurações de Swap

      Há algumas opções que você pode configurar que terão um impacto no desempenho do seu sistema quando estiver lidando com o swap.

      Ajustando a propriedade Swappiness

      O parâmetro swappiness configura a frequência com que o seu sistema transfere dados da RAM para o espaço de swap. Esse é um valor entre 0 e 100 que representa uma porcentagem.

      Com valores próximos de zero, o kernel não irá transferir dados para o disco a menos que seja absolutamente necessário. Lembre-se, as interações com o arquivo de swap são “dispendiosas”, no sentido de que demoram mais que as interações com a RAM e podem causar uma redução significativa no desempenho. Dizer ao sistema para não depender tanto do swap irá geralmente tornar o seu sistema mais rápido.

      Valores que estão mais próximos de 100 irão tentar colocar mais dados no swap em um esforço para manter mais espaço da RAM livre. Dependendo do perfil de memória de seus aplicativos ou do motivo pelo qual você está usando o seu servidor, isso pode ser melhor em alguns casos.

      Podemos ver o valor atual do parâmetro swappiness digitando:

      • cat /proc/sys/vm/swappiness

      Output

      60

      Para um desktop, um valor de swappiness de 60 não é um valor ruim. Para um servidor, você pode deixá-lo mais próximo de 0.

      Podemos definir o parâmetro swappiness para um valor diferente usando o comando sysctl.

      Por exemplo, para definir o valor do parâmetro swappiness em 10, poderíamos digitar:

      • sudo sysctl vm.swappiness=10

      Output

      vm.swappiness = 10

      Este valor persistirá até a próxima reinicialização. Podemos definir este valor automaticamente na reinicialização, adicionando a linha no nosso arquivo /etc/sysctl.conf:

      • sudo nano /etc/sysctl.conf

      No final, você pode adicionar:

      /etc/sysctl.conf

      vm.swappiness=10
      

      Salve e feche o arquivo quando você terminar.

      Ajustando a Configuração da Pressão por Cache

      Outro valor relacionado que você pode querer modificar é o vfs_cache_pressure. Este ajuste configura o quanto o sistema escolherá para as informações cache dos objetos inode e dentry em detrimento de outros dados.

      Basicamente, tratam-se de dados de acesso sobre o sistema de arquivos. De maneira geral, isso é difícil de consultar e, com frequência, muito solicitado. Assim, é algo muito bom que o seu sistema armazene dados em cache. Você pode ver o valor atual questionando o sistema de arquivos proc novamente:

      • cat /proc/sys/vm/vfs_cache_pressure

      Output

      100

      Uma vez que ele está atualmente configurado, o nosso sistema remove as informações de inode do cache muito rapidamente. Podemos definir isso em um valor mais conservador como 50, digitando:

      • sudo sysctl vm.vfs_cache_pressure=50

      Output

      vm.vfs_cache_pressure = 50

      Novamente, isso é apenas válido para a nossa sessão atual. Podemos alterar esse valor, adicionando-o ao nosso arquivo de configuração como fizemos com a nossa configuração do parâmetro swappiness:

      • sudo nano /etc/sysctl.conf

      No final, adicione a linha que especifica o seu novo valor:

      /etc/sysctl.conf

      vm.vfs_cache_pressure=50
      

      Salve e feche o arquivo quando você terminar.

      Conclusão

      Seguir as etapas deste guia lhe dará algum espaço para respirar em casos que de outra forma conduziriam a exceções de falta de memória. O espaço de swap pode ser incrivelmente útil para evitar alguns desses problemas comuns.

      Se você está encontrando erros de OOM (out of memory - falta de memória), ou se você descobrir que o seu sistema não consegue usar os aplicativos de que você precisa, a melhor solução é otimizar as configurações do seu aplicativo ou atualizar o seu servidor.



      Source link

      How To Add Swap Space on Debian 10


      Introduction

      One of the easiest way of guarding against out-of-memory errors in applications is to add some swap space to your server. In this guide, we will cover how to add a swap file to a Debian 10 server.

      Warning: Although swap is generally recommended for systems using traditional spinning hard drives, using swap with SSDs can cause issues with hardware degradation over time. Due to this consideration, we do not recommend enabling swap on DigitalOcean or any other provider that uses SSD storage. Doing so can impact the reliability of the underlying hardware for you and your neighbors. This guide is provided as reference for users who may have spinning disk systems elsewhere.

      If you need to improve the performance of your server on DigitalOcean, we recommend upgrading your Droplet. This will lead to better results in general and will decrease the likelihood of contributing to hardware issues that can affect your service.

      What is Swap?

      Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM. Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

      The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fallback for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

      Step 1 – Checking the System for Swap Information

      Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

      We can see if the system has any configured swap by typing:

      If you don't get back any output, this means your system does not have swap space available currently.

      You can verify that there is no active swap using the free utility:

      Output

      total used free shared buff/cache available Mem: 990Mi 36Mi 863Mi 4.0Mi 89Mi 837Mi Swap: 0B 0B 0B

      As you can see in the Swap row of the output, no swap is active on the system.

      Step 2 – Checking Available Space on the Hard Drive Partition

      Before we create our swap file, we'll check our current disk usage to make sure we have enough space. Do this by entering:

      Output

      Filesystem Size Used Avail Use% Mounted on udev 488M 0 488M 0% /dev tmpfs 100M 4.5M 96M 5% /run /dev/vda1 25G 989M 23G 5% / tmpfs 499M 0 499M 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 499M 0 499M 0% /sys/fs/cgroup tmpfs 100M 0 100M 0% /run/user/1001

      The device with / in the Mounted on column is our disk in this case. We have plenty of space available in this example (only 1.4G used). Your usage will probably be different.

      Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

      Step 3 – Creating a Swap File

      Now that we know our available hard drive space, we can create a swap file on our filesystem. We will allocate a file of the swap size that we want called swapfile in our root (/) directory.

      The best way of creating a swap file is with the fallocate program. This command instantly creates a file of the specified size.

      Since the server in our example has 1G of RAM, we will create a 1G file in this guide. Adjust this to meet the needs of your own server:

      • sudo fallocate -l 1G /swapfile

      We can verify that the correct amount of space was reserved by typing:

      Output

      -rw-r--r-- 1 root root 1.0G May 29 17:34 /swapfile

      Our file has been created with the correct amount of space set aside.

      Step 4 – Enabling the Swap File

      Now that we have a file of the correct size available, we need to actually turn this into swap space.

      First, we need to lock down the permissions of the file so that only the users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

      Make the file only accessible to root by typing:

      Verify the permissions change by typing:

      Output

      -rw------- 1 root root 1.0G May 29 17:34 /swapfile

      As you can see, only the root user has the read and write flags enabled.

      We can now mark the file as swap space by typing:

      Output

      Setting up swapspace version 1, size = 1024 MiB (1073737728 bytes) no label, UUID=b591444e-c12b-45a6-90fc-e8b24c67c006f

      After marking the file, we can enable the swap file, allowing our system to start using it:

      Verify that the swap is available by typing:

      Output

      NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -2

      We can check the output of the free utility again to corroborate our findings:

      Output

      total used free shared buff/cache available Mem: 990Mi 37Mi 860Mi 4.0Mi 92Mi 834Mi Swap: 1.0Gi 0B 1.0Gi

      Our swap has been set up successfully and our operating system will begin to use it as necessary.

      Step 5 – Making the Swap File Permanent

      Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

      Back up the /etc/fstab file in case anything goes wrong:

      • sudo cp /etc/fstab /etc/fstab.bak

      Add the swap file information to the end of your /etc/fstab file by typing:

      • echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

      Next we'll review some settings we can update to tune our swap space.

      Step 6 – Tuning your Swap Settings

      There are a few options that you can configure that will have an impact on your system's performance when dealing with swap.

      Adjusting the Swappiness Property

      The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

      With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are "expensive" in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

      Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications' memory profile or what you are using your server for, this might be better in some cases.

      We can see the current swappiness value by typing:

      • cat /proc/sys/vm/swappiness

      Output

      60

      For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

      We can set the swappiness to a different value by using the sysctl command.

      For instance, to set the swappiness to 10, we could type:

      • sudo sysctl vm.swappiness=10

      Output

      vm.swappiness = 10

      This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

      • sudo nano /etc/sysctl.conf

      At the bottom, you can add:

      /etc/sysctl.conf

      vm.swappiness=10
      

      Save and close the file when you are finished.

      Adjusting the Cache Pressure Setting

      Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

      Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it's an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:

      • cat /proc/sys/vm/vfs_cache_pressure

      Output

      100

      As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:

      • sudo sysctl vm.vfs_cache_pressure=50

      Output

      vm.vfs_cache_pressure = 50

      Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting:

      • sudo nano /etc/sysctl.conf

      At the bottom, add the line that specifies your new value:

      /etc/sysctl.conf

      vm.vfs_cache_pressure=50
      

      Save and close the file when you are finished.

      Conclusion

      Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these common problems.

      If you are running into OOM (out of memory) errors, or if you find that your system is unable to use the applications you need, the best solution is to optimize your application configurations or upgrade your server.



      Source link

      How To Add Swap Space on Debian 8


      Introduction

      One of the easiest way of guarding against out-of-memory errors in applications is to add some swap space to your server. In this guide, we will cover how to add a swap file to a Debian 8 server.

      Warning: Although swap is generally recommended for systems using traditional spinning hard drives, using swap with SSDs can cause issues with hardware degradation over time. Due to this consideration, we do not recommend enabling swap on DigitalOcean or any other provider that utilizes SSD storage. Doing so can impact the reliability of the underlying hardware for you and your neighbors. This guide is provided as reference for users who may have spinning disk systems elsewhere.

      If you need to improve the performance of your server on DigitalOcean, we recommend upgrading your Droplet. This will lead to better results in general and will decrease the likelihood of contributing to hardware issues that can affect your service.

      What is Swap?

      Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM. Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

      The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fallback for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

      Step 1 – Checking the System for Swap Information

      Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

      We can see if the system has any configured swap by typing:

      If you don't get back any output, this means your system does not have swap space available currently.

      You can verify that there is no active swap using the free utility:

      Output

      total used free shared buffers cached Mem: 1.0G 331M 668M 4.3M 11M 276M -/+ buffers/cache: 44M 955M Swap: 0B 0B 0B

      As you can see in the Swap row of the output, no swap is active on the system.

      Step 2 – Checking Available Space on the Hard Drive Partition

      Before we create our swap file, we'll check our current disk usage to make sure we have enough space. Do this by entering:

      Output

      Filesystem Size Used Avail Use% Mounted on /dev/vda1 25G 946M 23G 4% / udev 10M 0 10M 0% /dev tmpfs 201M 4.3M 196M 3% /run tmpfs 501M 0 501M 0% /dev/shm tmpfs 5.0M 0 5.0M 0% /run/lock tmpfs 501M 0 501M 0% /sys/fs/cgroup tmpfs 101M 0 101M 0% /run/user/1001

      The device with / in the Mounted on column is our disk in this case. We have plenty of space available in this example (only 946M used). Your usage will probably be different.

      Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

      Step 3 – Creating a Swap File

      Now that we know our available hard drive space, we can go about creating a swap file within our filesystem.

      We will create a file called swapfile in our root (/) directory. The file must allocate the amount of space we want for our swap file. There are two main ways of doing this:

      The Traditional, Slow Way

      Traditionally, we would create a file with preallocated space by using the dd command. This versatile disk utility writes from one location to another location.

      We can use this to write zeros to the file from a special device in Linux systems located at /dev/zero that just spits out as many zeros as requested.

      We specify the file size by using a combination of bs for block size and count for the number of blocks. What we assign to each parameter is almost entirely arbitrary. What matters is what the product of multiplying them turns out to be.

      For instance, in our example, we're looking to create a 1 Gigabyte file. We can do this by specifying a block size of 1 megabyte and a count of 1024:

      • sudo dd if=/dev/zero of=/swapfile bs=1M count=1024

      Output

      1024+0 records in 1024+0 records out 1073741824 bytes (1.1 GB) copied, 1.36622 s, 786 MB/s

      Check your command before pressing ENTER because this has the potential to destroy data if you point the of (which stands for output file) to the wrong location.

      We can see that 1 Gigabyte has been allocated by typing:

      Output

      -rw-r--r-- 1 root root 1.0G May 30 15:07 /swapfile

      If you've completed the command above, you may notice that it took a few seconds. Only 1.3 seconds for this small swapfile, but that could increase significantly for larger files on slower hard drives.

      If you want to learn how to create the file faster, remove the file swapfile using sudo rm /swapfile, then follow along below:

      The Faster Way

      The quicker way of getting the same file is by using the fallocate program. Note that this command only works with more modern filesystems, so if you're using an ext3 system, for instance, this option is not available to you.

      The fallocate command creates a file of a preallocated size instantly, without actually having to write dummy contents.

      We can create a 1 Gigabyte file by typing:

      sudo fallocate -l 1G /swapfile
      

      The prompt will be returned to you almost immediately. We can verify that the correct amount of space was reserved by typing:

      Output

      -rw-r--r-- 1 root root 1.0G May 30 15:07 /swapfile

      As you can see, our file is created with the correct amount of space set aside.

      Step 4 – Enabling the Swap File

      Now that we have a file of the correct size available, we need to actually turn this into swap space.

      First, we need to lock down the permissions of the file so that only the users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

      Make the file only accessible to root by typing:

      Verify the permissions change by typing:

      Output

      -rw------- 1 root root 1.0G May 29 17:34 /swapfile

      As you can see, only the root user has the read and write flags enabled.

      We can now mark the file as swap space by typing:

      Output

      Setting up swapspace version 1, size = 1048572 KiB no label, UUID=757ee0b7-db04-46bd-aafb-adf6954ea077

      After marking the file, we can enable the swap file, allowing our system to start utilizing it:

      Verify that the swap is available by typing:

      Output

      NAME TYPE SIZE USED PRIO /swapfile file 1024M 0B -1

      We can check the output of the free utility again to corroborate our findings:

      Output

      total used free shared buffers cached Mem: 1.0G 925M 74M 4.3M 13M 848M -/+ buffers/cache: 63M 936M Swap: 1.0G 0B 1.0G

      Our swap has been set up successfully and our operating system will begin to use it as necessary.

      Step 5 – Making the Swap File Permanent

      Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

      Back up the /etc/fstab file in case anything goes wrong:

      • sudo cp /etc/fstab /etc/fstab.bak

      Add the swap file information to the end of your /etc/fstab file by typing:

      • echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

      Next we'll review some settings we can update to tune our swap space.

      Step 6 – Tuning your Swap Settings

      There are a few options that you can configure that will have an impact on your system's performance when dealing with swap.

      Adjusting the Swappiness Property

      The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

      With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are "expensive" in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

      Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications' memory profile or what you are using your server for, this might be better in some cases.

      We can see the current swappiness value by typing:

      • cat /proc/sys/vm/swappiness

      Output

      60

      For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

      We can set the swappiness to a different value by using the sysctl command.

      For instance, to set the swappiness to 10, we could type:

      • sudo sysctl vm.swappiness=10

      Output

      vm.swappiness = 10

      This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

      • sudo nano /etc/sysctl.conf

      At the bottom, you can add:

      /etc/sysctl.conf

      vm.swappiness=10
      

      Save and close the file when you are finished.

      Adjusting the Cache Pressure Setting

      Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

      Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it's an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:

      • cat /proc/sys/vm/vfs_cache_pressure

      Output

      100

      As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:

      • sudo sysctl vm.vfs_cache_pressure=50

      Output

      vm.vfs_cache_pressure = 50

      Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting:

      • sudo nano /etc/sysctl.conf

      At the bottom, add the line that specifies your new value:

      /etc/sysctl.conf

      vm.vfs_cache_pressure=50
      

      Save and close the file when you are finished.

      Conclusion

      Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these common problems.

      If you are running into OOM (out of memory) errors, or if you find that your system is unable to use the applications you need, the best solution is to optimize your application configurations or upgrade your server.



      Source link