Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heroku (Docker) PORT environment variable in nginx

I just take a few modifications on a Dockerfile to run it with nginx on Heroku. Something special about Heroku is, that everything is running as non-root. Second certain behaviour is the use of a random Port which comes from Heroku itself and you can't be modified. They provide the env $PORT which you should bind to nginx. If Heroku recognizes that something isn't bind to that port it stops the entire container. Question is:

How can I bind nginx to a given env variable in order to have a dynamic port in the nginx-site.conf? I tried to use things like follows in the Dockefile:

env PORT; in nginx.conf and listen PORT_from_env; in the nginx-site.conf Also tried listen 80; in the nginx-site.conf and RUN /bin/sed -i "s/listen 80/listen ${PORT}/" /etc/nginx/sites-available/default.conf in the Dockerfile

I am absolutely above my capabilities. Someone has an idea or can help? It be very helpful!


Further information:

  • https://devcenter.heroku.com/articles/dynos#web-dynos
like image 586
Marjan Avatar asked Mar 07 '18 08:03

Marjan


1 Answers

I got it working for my app by following this example :

Step 1: listen to $PORT in default.conf.template

server {
  listen $PORT default_server;

  location / {
    root   /usr/share/nginx/html;
    index  index.html;
  }
}

Step 2: add this directive to your Dockerfile

COPY default.conf.template /etc/nginx/conf.d/default.conf.template

Step 3: add this at the end of your Dockerfile

CMD /bin/bash -c "envsubst '\$PORT' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
like image 123
Jimmy Avatar answered Oct 07 '22 05:10

Jimmy