Add Swap Memory on Fly.io Container

Fly.io

Related Posts

All discussions about programming technologies and other technologies
As we move into 2025, the programming world is set ...
Fly.io
For those of you currently using shared hosting to publish ...
All discussions about programming technologies and other technologies
As technology advances at an unprecedented pace, 2024 has seen ...

When we’re faced with an environment with limited RAM, it can sometimes impact system performance. One solution to address the significant impact caused by a full RAM condition is to use swap memory. So this is how to add swap memory on your Fly.io container. If you are new to use Fly.io, you can read this article.

What is swap memory?

Swap memory is a part of your storage (like a hard drive or SSD) that your computer uses as extra memory when the physical RAM is full. It works like a backup space, where less-used data from RAM is temporarily moved to make room for more important tasks. While it helps prevent crashes when RAM runs out, swap is much slower than real RAM, so using it too much can make your computer feel sluggish. But in some cases, this is necessary to overcome errors that may occur when the RAM is full. So, it can be good to add swap memory when you create Fly.io container. In my case, I only set small RAM for my wordpress container, sometimes it running out and I cannot open my website anymore. I add 512mb swap memory to my container, and it very help me to prevent this issue.

How to do this?

First of all, you have to create all configuration for you container first and ensure it’s running well. After that, add this line to your Dockerfile to add swap memory to your container .

# Enable swap on container start
CMD sh -c "fallocate -l 512M /.fly-upper-layer/swapfile && chmod 600 /.fly-upper-layer/swapfile && mkswap /.fly-upper-layer/swapfile && swapon /.fly-upper-layer/swapfile && <your-script-to-start-app>"

For my wordpress application, this is full script of Dockerfile:

FROM wordpress:6.8.1-php8.1-apache

# Install nano and mysql client
RUN apt-get update && \
    apt-get install -y nano default-mysql-client && \
    a2enmod rewrite headers && \
    rm -rf /var/lib/apt/lists/*

# Optional PHP config (upload limit, etc.)
COPY ./php.ini /usr/local/etc/php/conf.d/uploads.ini

# Enable swap on container start
CMD sh -c "fallocate -l 512M /.fly-upper-layer/swapfile && chmod 600 /.fly-upper-layer/swapfile && mkswap /.fly-upper-layer/swapfile && swapon /.fly-upper-layer/swapfile && apache2-foreground"

WORKDIR /var/www/html
EXPOSE 80

After add this line, rebuild and deploy your container using fly.io deploy script

fly deploy

After process finish, you can show your swap memory by open Metrics on your Fly.io container.

Conclusion

Same like other environment, you can add swap memory for your Fly.io container to prevent error caused by full RAM case.

Scroll to Top