Enable swap file on an Elastic Beanstalk Docker Host

1 minute read

The Elastic Beanstalk Docker setup works by building the docker image on each host as part of the deployment process, rather than pulling a built image from a repository.

This means you don’t need to worry about configuring extra build steps and configuring authentication, but if you are running light weight hosts you might not have enough memory to actually build the image. Since the new image is built on the server while the current container is running you might find the initial deploy works when there is nothing else running, but then redeploying the app fails.

As a rule of thumb, if something works on your local machine, and it doesn’t work on a virtual server that doesn’t have a swap file set up, try adding one.

To set up a swap file, we can take advantage of the run time hooks Elastic Beanstalk offers - but documents poorly - and insert a script that will run before the docker run phase.


    command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/pre"
    ignoreErrors: true
    mode: "000755"
    owner: root
    group: root
    content: |


      if [ -f $SWAPFILE ]; then
        echo "Swapfile $SWAPFILE found, skipping"
        exit 0;

      /bin/dd if=/dev/zero of=$SWAPFILE bs=1M count=$SWAP_MEGABYTES
      /bin/chmod 600 $SWAPFILE
      /sbin/mkswap $SWAPFILE
      /sbin/swapon $SWAPFILE
      exit 0;

This works by adding the script into /opt/elasticbeanstalk/hooks/appdeploy/pre which is then picked up by Elastic Beanstalk and executed before deploying the app. pre indicating the before element, and appdeploy been the deployment stage.

Next steps

In theory, you don’t want to be using the swap file when the image is running, so you could remove the swap file once the image is built.

Read More In The Official AWS Docs

The deployment stages and hooks that you can use are documented on AWS at https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/custom-platform-hooks.html if you want to expand on this pattern.


I came by the original details for this on a gist: https://gist.github.com/steinnes/1f8a1b44fed4b136005f