Modify nginx configuration files on an AWS Elastic Beanstalk environment

aws nginx linux

October 11, 2020

After spending a whole day trying to modify nginx.conf on app deployment and going through AWS endless documentation, I finally succeeded and wanted to share it with you.
Note: the following procedure can be used to execute any script or modify any file on application deployment.
Creating a custom nginx.conf directly in /etc/nginx/ via a .config file in .ebextensions didn't work for me as it would be systematically overwritten by the default one.
Same thing happened when I created the custom file in /tmp and wrote a container_command that would replace /etc/nginx/nginx.conf.
You actually need to create a script that will be executed after deployment, after Elastic Beanstalk has written all your files.
You are using an Amazon Linux 1 environment
Source: AWS documentation
To execute any script after deployment put the following code into your .config file at the root of .ebextensions
Create a directory that will store your script.
1 commands: 2 create_post_dir: 3 command: "mkdir /opt/elasticbeanstalk/hooks/appdeploy/post" 4 ignoreErrors: true
Create your modified nginx.conf file and place it in /tmp.
6 files: 7 "/tmp/custom_nginx.conf": 8 mode: "000644" 9 owner: root 10 group: root 11 content: | 12 # your .conf file
Create a script that will replace the original nginx.conf by your custom one in /opt/elasticbeanstalk/hooks/appdeploy/post created at step 1. This should be automatically executed after deployment.
14 "/opt/elasticbeanstalk/hooks/appdeploy/post/": 15 mode: "000644" 16 owner: root 17 group: root 18 content: 19 #!/usr/bin/bash 20 sudo mv /tmp/custom_nginx.conf /etc/nginx/nginx.conf
You are using an Amazon Linux 2 environment
Source: AWS documentation
Scripts are now executed from subfolders in .platform that you have to place at the root of your project, like so:
~/app/ |-- |-- static | |-- styles.css |-- templates | |-- index.html |-- |-- .ebextensions/ | |-- 01_write_custom_ng_conf.config |-- .platform/ |-- hooks |-- postdeploy |-- # Executed post deployment
Create a .config file at the root of .ebextensions.
Create your modified nginx.conf file and place it in /tmp.
1 files: 2 "/tmp/custom_nginx.conf": 3 mode: "000644" 4 owner: root 5 group: root 6 content: | 7 # your .conf file
Create a small script in .platform/hooks/postdeploy and change permissions to 755.
1 #!/usr/bin/bash 2 3 # Replace the original nginx.conf by our custom one 4 sudo mv /tmp/custom_nginx.conf /etc/nginx/nginx.conf 5 6 # Restart nginx to apply modifications 7 sudo service nginx restart
This method should work for any environment running on a Amazon Linux 2 instance.
Note: Make sure that your .config files indentation is perfect as errors are not always detected by the parser and the code won't be executed.