The "prod" Environment
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
With a Subscription, click any sentence in the script to jump to that part of the video!
Login SubscribeOur app is currently running in the dev environment. Let's switch it to prod... which is what you would use on production. Temporarily change APP_ENV=dev to prod:
| // ... lines 1 - 15 | |
| ###> symfony/framework-bundle ### | |
| APP_ENV=prod | |
| // ... lines 18 - 20 |
then head over and refresh. Whoa! The web debug toolbar is gone. That... makes sense! The entire web profiler bundle is not enabled in the prod environment.
You'll also notice that the dump from our controller appears on the top of the page. The web profiler normally captures that and displays it down on the web debug toolbar. But... since that whole system isn't enabled anymore, it now dumps right where you call it.
And there are a lot of other differences, like the logger, which now behaves differently thanks to the configuration in monolog.yaml.
Clearing the prod Cache
The way pages are built has also changed. For example, Symfony caches a lot of files... but you don't notice that in the dev environment. That's because Symfony is super smart and rebuilds that cache automatically when we change certain files. However, in the prod environment, that doesn't happen.
Check it out! Open up templates/base.html.twig... and change the title on the page to Stirred Vinyl. If you go back over and refresh... look up here! No change! The Twig templates themselves are cached. In the dev environment, Symfony rebuilds that cache for us. But in the prod environment? Nope! We need to clear it manually.
How? At your terminal, run:
php bin/console cache:clear
Notice it says that it's clearing the cache for the prod environment. So, just like how our app always runs in a specific environment, the console commands also run in a specific environment. And, it reads that same APP_ENV flag. So because we have APP_ENV=prod here, cache:clear knew that it should run in the prod environment and clear the cache for that environment.
Thanks to this, when we refresh... now the title updates. I'll change this back to our cool name, Mixed Vinyl.
Changing the Cache Adapter for prod Only
Let's try something else! Open up config/packages/cache.yaml. Our cache service currently uses the ArrayAdapter, which is a fake cache. That might be cool for development, but it won't be much help on production:
| framework: | |
| cache: | |
| // ... lines 3 - 10 | |
| app: cache.adapter.array | |
| // ... lines 12 - 25 |
Let's see if we can switch that back to the filesystem adapter, but only for the prod environment. How? Down here, use when@prod and then repeat the same keys. So framework, cache, and then app. Set this to the adapter we want, which is called cache.adapter.filesystem:
| framework: | |
| cache: | |
| // ... lines 3 - 10 | |
| app: cache.adapter.array | |
| // ... lines 12 - 20 | |
| when@prod: | |
| framework: | |
| cache: | |
| app: cache.adapter.filesystem |
It's going to be really easy to see if this works because we're still dumping the cache service in our controller. Right now, it's an ArrayAdapter. If we refresh... surprise! It's still an ArrayAdapter. Why? Because we're in the prod environment... and pretty much any time you make a change in the prod environment, you need to rebuild your cache.
Go back to your terminal and run
php bin console cache:clear
again and now... got it - FilesystemAdapter!
But... let's reverse this config. Copy cache.adapter.array and change it to filesystem. We'll use that by default. Then at the bottom, change to when@dev, and this to cache.adapter.array:
| framework: | |
| cache: | |
| // ... lines 3 - 10 | |
| app: cache.adapter.filesystem | |
| // ... lines 12 - 20 | |
| when@dev: | |
| framework: | |
| cache: | |
| app: cache.adapter.array |
Why am I doing that? Well, that literally makes zero difference in the dev and prod environments. But if we decide to start writing tests later, which run in the test environment, with this new config, the test environment will use the same cache service as production... which is probably more realistic and better for testing.
To make sure this still works, clear the cache one more time. Refresh and... it does! We still have FilesystemAdapter. And... if we switch back to the dev environment in .env:
| // ... lines 1 - 15 | |
| ###> symfony/framework-bundle ### | |
| APP_ENV=dev | |
| // ... lines 18 - 20 |
and refresh... yes! The web debug toolbar is back, and down here, we are once again using ArrayAdapter!
Now, in reality, you probably won't ever switch to the prod environment while you're developing locally. It's hard to work with... and there's just no point! The prod environment is really meant for production! And so, you will run that bin/console cache:clear command during deployment... but probably almost never on your local machine.
Before we go on, head into VinylController, go down to browse(), and take out that dump():
| // ... lines 1 - 12 | |
| class VinylController extends AbstractController | |
| { | |
| // ... lines 15 - 32 | |
| ('/browse/{slug}', name: 'app_browse') | |
| public function browse(HttpClientInterface $httpClient, CacheInterface $cache, string $slug = null): Response | |
| { | |
| $genre = $slug ? u(str_replace('-', ' ', $slug))->title(true) : null; | |
| $mixes = $cache->get('mixes_data', function(CacheItemInterface $cacheItem) use ($httpClient) { | |
| $cacheItem->expiresAfter(5); | |
| $response = $httpClient->request('GET', 'https://raw.githubusercontent.com/SymfonyCasts/vinyl-mixes/main/mixes.json'); | |
| return $response->toArray(); | |
| }); | |
| return $this->render('vinyl/browse.html.twig', [ | |
| 'genre' => $genre, | |
| 'mixes' => $mixes, | |
| ]); | |
| } | |
| } |
Okay, status check! First, everything in Symfony is done by a service. Second, bundles give us services. And third, we can control how those services are instantiated via the different bundle configuration in config/packages/.
Now, let's go one important step further by creating our own service.
21 Comments
Sorry to bother you on an "old" chapter, but I tried to upload a new app made (proudly ^^) with Symfony 6.4 (yeah I started that before the release of S7), and I have a "not very explicit" error:
Attempted to call function "putenv" from namespace "Symfony\Component\HttpKernel".
...and that's it.
I guess it has something to do with this chapter, but I have no idea how to solve it, and Google doesn't help at all. I never had it before, and of course, "the app runs perfectly on my pc", both on dev and prod mod.
Beside I have very little control on the server for this app. I just know that it runs on PHP 8.3, I have control only over a few vars, but I can have potential support from the company - I guess... I must sadly add that I know almost nothing about servers configuration.
Could you please guide me through that? It's quite frustrating ^^
Thank you.
Aaaaah! I got it! It was a doctrine configuration error! It could have been a bit more explicit error...
Thanks anyway, Symfonycasts remains by far the best site about Symfony.
Now that my new app runs smoothly I can go and learn S7...See you soon ;)
Edit: nooo, sorry, scratch that! It doesn't run smoothly yet, and it's kinda weird. On dev mode, I still have that same blocking (not explicit :p) error. But on dev mode, I now have 404 on every requests: login, api, etc. But I also have a new error in the firefox console: (in french, sorry)
Blocage d’une requête multiorigines (Cross-Origin Request) : la politique « Same Origin » ne permet pas de consulter la ressource distante située sur https://www.mybeautifulsymfonysite.fr/api/tags?isTheStar=true. Raison : l’en-tête CORS « Access-Control-Allow-Origin » est manquant. Code d’état : 404.
I guess that's still an .env problem.
Edit day 2:
I'm still struggling with that problem. Now I don't get anymore that putenv error, only CORS errors. I tried so many nelmio cors confiigurations that I kinda lost track ^^. I'm at a point where (I think) i authorized everything from everywhere, yet it doesn't work. Now I'm trying to get rid of Nelmio and try something else.
Hey Jean,
Hm, that sounds like you need to add a back slash in front of that function, i.e.
\putenv(). The only question is, do you call that function in your code or is it something that's called in the code from vendor/ dir that you can't touch. if first one - you can easily fix it yourself I think. Otherwise, you may try to fix it with that back slash in vendors just to give it a try and see if that helps. But the proper fix might be to upgrade related dependencies were that is fixed already. I see you updated the comment saying you don't have that error anymore and I wonder how you fixed that :)About the CORS problem, are you using custom written API? OR do you use ApiPlatform? Because with ApiPlatofm that might be already configured for you and should work out of the box.
Btw, that page give 404 error. Please, make sure that the same exact
/api/tags?isTheStar=trueURL works locally for you. If it works, go ssh to the prod server and make sure you have that route there, you can runbin/console debug:router --env=prodand check for that/api/tagsexist there. You may also want to runcache:clear --env=prodandcache:warmup --env=prodcommands to make sure you refresh the old cache on prod, that's important to do after the deploy process, depends on your deploy strategy.But if you have customly written API - make sure you have
nelmio/cors-bundleproperly installed and enabled in bundles.php. Then maybe try the next config in yourconfig/packages/nelmio_cors.yaml:If you made those changes directly on prod - don't forget to clear the cache every time you change your config! Otherwise no changes will be applied.
After you add that CORS config - make sure you have CORS headers when do new requests to the https://www.mybeautifulsymfonysite.fr/api/tags?isTheStar=true - you can do it in the Chrome dev toolbar for example, or using
curlin the CLI:The response should have correct headers.
If it finally works - then you may try a more strict config - instead of
*use specific domains, .e.ghttps://www.mybeautifulsymfonysite.frif all your API requests goes from there. P.s. are you sure you're using the correct domain? Because that host does not work for me at all, probably a misconfiguration on the server, you should make the host work first to be able to try those API requests.And last but not least, try to check the logs in
var/log/prod.logjust in case, you can even track them in real time withtail -f var/log/prod.logand try to do the request. Sometimes logs may contain useful hints too.I hope that helps!
Cheers!
Thank you for your reply. I use Nelmio Cors and haven't written anything about putenv() ever, anywhere. Il's a very basic symfony configuration, mainly inspired by your work here. I never touched the vendor dir and I use Api Platform (sometimes i regret it ^^).
The putenv error only appears in prod mode on my server. In dev mode I can get to the fronthome but absolutely no requests are accepted. When I'm at "https://WWW.mydomain.fr" I only get 404s. It's without the "WWW" that I get the "cross origin requests" error, resulting into a 404. Www or not, I get 404s also on /login, not only api's calls.
And this is what I get when I do your curl call:
HTTP/1.1 200 OK<br />date: Fri, 15 Nov 2024 13:12:18 GMT<br />server: Apache<br />allow: GET,POST,OPTIONS,HEAD<br />vary: User-Agent<br />content-length: 0<br />set-cookie: WEBMO-MNO=11115|ZzdIt|ZzdIt; path=/; HttpOnly; SameSite=StrictI'll keep trying. Thanks anyway for your input.
Edit: so I tried again everyting in local with your Nelmio configuration above. Absolutely no errors anywhere, dev or prod, every urls are ok. I can get to the./api page docs.
For the server I switch the database url to the right one, updates Axios baseUrl, and that's it. And clear cache each time I try something new.
Edit2: in the prod cache on the server I can read url_generating_routes.php and I can see that all the routes are indeed there: login, logout, admin section and all the apis. I'm not sure that means anything, though ^^'
Coud it be some configuration on my server that causes my problem? Or is it obviously something i did wrong on my side, somewhere? What should be the correct answer of that curl call?
Day XXX: I rebuilt entirely my app with the latest versions of everything. It took a while and some updates where...tricky to say the least. Anyway, no more putenv error with the new version, which is nice, but still cors errors everywhere. And yet I think I allowed everything:
Nothing works, and I voluntarily admit that I know nothing about CORS and.. I don't want to learn that, I have enough on my plate. I'm quite desperate and I've no clue about how to debug this: no method, no idea, no nothing.
Hey Jean,
Oh, that's a bummer to entirely rebuild everything. I'm happy to hear you don't have that putenv error anymore... that sounds like it was either a problem with dependencies that were fixed in a newer version of a package, or you have misconfiguration maybe. It is difficult to say without proper debugging.
About the CORS, that's indeed annoying. Unfortunately, our bandwidth is limited and we can't help with issues from customer personal projects. If you could share more details about what config CORS you have and what exactly you're trying to do when you see that error - I could try to take a look one more time, probably I will have some ideas where to move with it. But it sounds like you need a proper debugging, first of all, you need to debug the server response to make sure that you have those CORS related headers set correctly in that. Difficult to say for sure if it's a server config problem or your app config problem without understanding the request, response, the actions you're doing and the CORS error you see.
Cheers!
Hello,
I have developed an app in 6.2 which works perfectly in dev, but when i swith to prod it will not work anymore. I've cleared the caches but this doesn't change the issue.
The log talks about "Authenticator does not support the request." and "Did you forget to run \"composer require symfony/twig-bundle\"? As I said: in dev-mode the app works perfectly.
Any ideas ? Thanks
Hey @Domingo987
That's odd. From the error, I believe you're not loading the
TwigBundlefor the prod environment. Check yourbundles.phpfile to see if it loads that bundle. Also, I may recommend to re-install your vendor directoryLet me know if that helped. Cheers!
Thanks for suggestions but nothing will work. I've done a composer update, I've checked the bundles, cleared the caches.
I work with Symfony since Symfony 4. Its the first time that the prod environement will not work as the dev.
I put here the log :
Thanks for any suggestions
Interesting... Have you checked your config and service files for some weird, prod-specific config? If that's not the case I believe the error message is misleading. Try disabling xDebug, it sometimes causes a weird behavior
I am an "end user". I have started a new project from scratch. For the moment the dev and the prod work both well.
Thanks for your help.
Hi team,
I'm absolutly disappointed. Since 2 dys I try to install py project on a server (Website). I respect all in how to deploy, and no css, js... . I use webpack encore and commands "yarn encore production" & "yarn build run" works fine in my computer. Have you an idea? (I clear cache php bin/console cache:clear --env=prod and delete folder "cache" before sftp transfert)
Thank' in advance
For completed I note that webpack doesn't point in the good directory : in console error it search build directory at the root, and in reality it could be find in public directory. How solve this? To solve this for the moment I make a copy of build in root directory. It works but it's not the solution. I have no subsdirectory.
Many thanks
Hi @Delenclos-A!
Well, we don't want that. So let me see if I can help :). And yes, I think I can see the problem! We CAN solve this problem with a tweak in your Webpack config. But actually, I can suggest a (hopefully) better solution overall for you.
Ok, so the site is installed at
http://potcommun.lamih.fr/public/login. The key thing I notice is that thepublicdirectory is in the URL. Even ignoring Webpack, that isn't ideal. I'm guessing it would be much nicer to just have the URL behttp://potcommun.lamih.fr/login. This would also fix the Webpack problem.On your host, you probably have a document root directory which is available to the public - let's pretend it is
/var/www. And so, you've deployed your app into this directory. This means you have a/var/www/publicdirectory with your application'sindex.phpinside of it. That's why you need to have the extra/publicin the URL: that executes the/var/www/public/index.phpfile.To remove the extra public, you have 2 options:
1) If you have access to your server configuration (e.g. Apache, Nginx, etc) and are able to, you could change the "document root" from
/var/www/to/var/www/public. This is really the only directory that should be public (right now, your entire project source is public - e.g.https://potcommun.lamih.fr/webpack.config.js2) Or, an often easier way is to use a symbolic link. That looks like this:
A) Deploy your app to some OTHER directory that is NOT served by your web server - e.g.
~/potcommun.B) Delete the web root - so literally
rm -rf /var/wwwC) Create a symbolic link from
/var/wwwto/potcommun/public. The command is:With this setup, your document root will STILL be
/var/www. But that is a symbolic link to thepublic/directory of your app.Please let me know if this helps!
Hi, great answer. Thank's to take time to help symfony's community. It works fine. I've changed the document root and it's just magic.
Have a good day and Thank's
In my environment, switching to prod does not show any dump on top of the page as in your video
Hey @Anatolie
I'm guessing you forgot to clear the cache for the prod environment. Could you double-check that?
Cheers!
Of course I cleared the cache.
That's odd. If you change something else, do you see it reflected?
When I just switch to 'prod', I get a 500 error, turns out I need to clear cache first before switching to 'prod', the steps are:
php bin/console cache:clear.envfile to switch to 'prod'Hey @Yulong!
Hmm. I'm not sure what happened in your situation, but normally you would need to switch steps 1 and 2. The idea is:
1) Edit
.envfile to switch toprod(at this point, if you refreshed, you WILL likely get a 500 error).2)
php bin/console cache:clear- because.envis set toprodthis will clear theprodcache. If you did this step before step 1, it would be clearing thedevcache, which is something you can do, but it wouldn't help in theprodenvironment.Anyways, I'm sure it was something minor - I just wanted to give you a bit more detail about the "why" behind the order of these steps. Btw, you can also run
php bin/console cache:clear --env=prodto clear the "prod" cache, regardless of whatAPP_ENVis set to in.env:).Cheers!
"Houston: no signs of life"
Start the conversation!