1
votes

I recently deployed a new Symfony 4 project to a prod server where I set (via ssh) both APP_ENV and APP_SECRET among others, as environment variables. Both commands printenv and set list those variables in their output so I assume everything should be fine on that part.

I get an error 500 on the site though, the log returning PHP Fatal error: Uncaught RuntimeException: APP_ENV environment variable is not defined. You need to define environment variables for configuration or add "symfony/dotenv" as a Composer dependency to load variables from a .env file.

What am I missing here ?

3

3 Answers

4
votes

[EDIT 2020] --> use the 'symfony/dotenv'

According to the how to deploy official documentation what you can do is to move 'symfony/dotenv' in your composer file from require-dev to require so it's installed also on production environement. Then you can keep using a .env.local file.

If you don't want or can't use the 'symfony/dotenv'

For Apache and on Ubuntu first you need mod_env activated

sudo a2enmod env
sudo service apache2 restart

Then put the environement variable in the .htacess or in the vhost config file. For SF4 the .htacess is in /public and here is the syntax. I don't know if order matter, I would say no, so I added them on the top of the file.

SetEnv APP_ENV prod
SetEnv APP_SECRET fjsdkfj...
SetEnv DATABASE_URL mysql://...

Now some random useful tricks :

  • You don't want to commit the .htaccess file. Add it to the shared part of your deployment tool. In my case (easy-deploy-bundle)

    ->sharedFilesAndDirs(['public/.htaccess'])
    
  • You'll need to copy the environment variables in /etc/environment so it's available by composer ... this one is a real pain in the ass, because now you duplicated your variables. So the Symfony team said env variable are betters because safer and standard. But duplicate the information is not safer at all. Maybe I'm doing it wrong (which is completly possible). If you know how to avoid this please share. The printenv command will show you if it's correctly configured.

  • If you use easy-deploy-bundle for production remove the --quiet option on composer so you have a clear error message if it fail (because it doesn't find the env variable for example). Also check that --no-dev option is here, so it won't install dotenv package.

    ->composerInstallFlags('--prefer-dist --no-interaction --no-dev')
    
2
votes

System variables won’t be available to your web server. The variable should be defined in the vhost/htaccess file. I assume you are using Apache.

1
votes

if you are using nginx have to defined at the end of pool configuration file.

php5

/etc/php5/fpm/pool.d/www.conf

php7

/etc/php/7.1/fpm/pool.d/www.conf