How to properly use ENV variables in Nginx config?

12,780

After some investigation it seems that passenger_app_env (which rails_env is aliased to) is not accepting the variable and instead treating it as a literal.

https://github.com/phusion/passenger-docker/issues/28

So, instead of $env_rails_env expanding to the content of the $RAILS_ENV read by lua, it's treated as a string $env_rails_env. That's why the log line is reporting database not configured.

Also, per nginx Q & A, variables shouldn't be used in configuration files:

"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html

What I ended up is using envsubst(1).

Share:
12,780

Related videos on Youtube

Clément Perroud
Author by

Clément Perroud

Unix/Linux enthusiasts. Hello, I'm Jakov. I currently work as a Systems Engineer I'm very passionate in Open Source Software and Unices (Linux, *BSD), networking and development. As a Myers-Briggs INFJ I insist on high quality and am purist at most times. I hate fast hacks and like the systems to be set up as cleanly as possible (everything packaged up in OS native packages, services deployed and configured with configuration management, etc).

Updated on September 18, 2022

Comments

  • Clément Perroud
    Clément Perroud over 1 year

    I want to pass the RAILS_ENV env variable to nginx and use it to set the value for the rails_env directive.

    I can read the value of the variable from the environment with LUA module:

    location @app {
        set_by_lua $env_rails_env 'return os.getenv("RAILS_ENV")';
        return 200 'rails env is: ${env_rails_env}';
    }
    

    When I curl it, I get the correct answer:

    [jsosic@workstation ~]$ curl http://localhost:3005/
    rails env is: development
    

    But, if I want to use it as a value for nginx directive:

    location @app {
        set_by_lua $env_rails_env 'return os.getenv("RAILS_ENV")';
        rails_env         $env_rails_env;
        limit_req         zone=one burst=100;
        passenger_enabled on;
    }
    

    I get the following log:

    Message from application: '${env_rails_env}' database is not configured.
    Available: ["default", "development", "test", "production"] 
    

    Is this even possible?