El entorno Prod
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 SubscribeAbre el archivo .env en la raíz de nuestro proyecto y cambia esta variable de entorno devpor prod.
| // ... lines 1 - 17 | |
| APP_ENV=prod | |
| // ... lines 19 - 20 |
Para ver qué ha cambiado, de vuelta a nuestro navegador, actualiza. Y... ¡eh! ¡Fíjate! La barra de herramientas de depuración web ha desaparecido. Ahora, intentemos cambiar algo en una de nuestras plantillas. Abre templates/main/homepage.html.twig y, en la parte inferior, cambiemos Time por Updated at para que sea más descriptivo.
| // ... lines 1 - 4 | |
| {% block body %} | |
| <main class="flex flex-col lg:flex-row"> | |
| // ... lines 7 - 54 | |
| <div> | |
| // ... lines 56 - 57 | |
| <p>Updated At: {{ issData.timestamp|date }}</p> | |
| // ... lines 59 - 62 | |
| </div> | |
| // ... line 64 | |
| </main> | |
| {% endblock %} |
Si volvemos atrás y actualizamos... no ha cambiado nada. ¿Por qué? Por razones de rendimiento, las plantillas se almacenan en caché. Hicimos nuestro cambio después de que la plantilla se almacenara en caché, por lo que nuestro navegador aún no puede verlo. Para solucionarlo, tenemos que borrar manualmente nuestra caché. En tu terminal, ejecuta:
bin/console cache:clear
Para especificar la caché del entorno que queremos borrar, podemos añadir la opción --env= con el nombre del entorno para el que queremos borrar la caché al final de este comando, como --env=prod, por ejemplo:
bin/console cache:clear --env=prod
Esto puede ser útil cuando necesites ejecutar un comando en un entorno específico distinto de aquél en el que estás trabajando actualmente. Como ya estamos desarrollando en el entorno prod, esta parte del comando no es necesaria. Si ejecutamos eso... ¡bien! La caché del entorno prod se ha borrado correctamente.
Bien, si volvemos y actualizamos la página de nuevo... ¡tachán! Vemos "Actualizado en". Fantástico. Si alguna vez trabajas en el entorno prod y no ves reflejados en el navegador los cambios que has hecho en tus plantillas, archivos de configuración, etc., puede que necesites borrar manualmente la caché.
Ahora mismo, estamos utilizando cache.adapter.array, que es algo así como una caché falsa. Podemos verlo en el archivo config/packages/cache.yaml. Una caché falsa está bien para el desarrollo, pero cuando estamos trabajando en el entorno prod, realmente queremos utilizar cache.adapter.filesystem en su lugar. Como ya conocemos la sintaxis de when@, aprovechémosla. A continuación, digamos when@, pero esta vez, tenemos que configurarlo en nuestro entorno prod con when@prod:. Debajo, repetiremos la misma estructura que vemos arriba - framework, cache, y app - seguidos de cache.adapter.filesystem.
| // ... lines 1 - 23 | |
| when@prod: | |
| framework: | |
| cache: | |
| app: cache.adapter.filesystem |
Bien, para ver esto en acción, necesitamos borrar la caché de nuevo (ya que aún estamos en el entorno prod ) con:
bin/console cache:clear
De vuelta a nuestro navegador, si observas atentamente, verás que nuestros datos se almacenan en caché durante unos cinco segundos, y luego... ¡nuevos datos! Funciona. En nuestro archivo .env, cambiemos APP_ENV=prod por dev. Si volvemos y actualizamos de nuevo... después de cada actualización... vemos una petición HTTP.
A continuación: Aprendamos más sobre los servicios.
7 Comments
Well, after changing from dev to prod I ended up with "Hey look at that: No CSS :("...
I think since asset mapper we have to manually build our assets in prod right?
Hey @elkuku ,
Did you try to clear the cache? Did you run all the required commands from the README file before start working with the start/ directory of the downloaded course code?
Cheers!
I doubt that clearing the cache would create the missing files but yes I ran the commands from the readme file (even the updated one...)
I am not sure what magic you have running on your end but as far as I understand the new asset mapper component it will only compile your assets in the dev environment while you have to run
bin/console asset-map:compileto have your assets available in prod.So.... What (the
F) am I missing here??Hey @elkuku ,
Sorry for confusing, I mean clear the browser cache, in Google Chrome you can do or while the Chrome dev tools panel is open, and you can press and hold the refresh browser button, then choose "Empty cache and hard reload". Though clearing the app cache is also a good idea, especially in prod as it may has some cached templates that were changed and so this may not include some necessary CSS files, etc. So I would recommend you both actually.
But once again, the steps you should do to boot the project with styles correctly:
composer installbin/console tailwind:build- this command is exactly the one that responsible for your styles look good, no matter of the Symfony env you're loading your app in.symfony serveorAPP_ENV=prod symfony servein case you want to run it in prodI just re-downloaded the course code myself again, moved to the finish/ dir, and followed all those steps from above. After this, when I load the app in the
prodmode - I do see styles, so no extra steps required for me.Which OS are you on? Are you following this course from the start/ dir? Are you using Symfony built-in dev server to spin the app? If your setup is a different one, probably you may have some misconfiguration.
Btw, you may want to rerun the
composer installcommand, does it fix the problem for you in prod? Becausecomposer.jsonhave some scripts that will be run during the install command. Or you can try to run them manually one by one to see if that will help.I hope this helps!
Cheers!
Hey @Victor,
Thanks for your detailed reply. Very much appreciated. Unfortunately I am still not able the find the error on my side :(
About my environment: I am running on a Linux system with the Symfony binary installed and I did exactly what is recommended in the readme file. Everything works just fine in the
devenvironment.I think I disagree on your point number 4. On my system the command
bin/console tailwind:buildwill build the CSS in/var/tailwind/tailwind.built.csswhich (I think) is somehow served by asset mapper in/public/assets/but only indev...When I switch to
prod(via the.envfile) I get a bunch of 404s trying to load the assets from/public/assetswhich does not exist until I do abin/console asset-map:compileafter which the site loads perfectly.But... I have noticed after several tests that sometimes the browser loads the assets from the cache after switching to
prodand sometimes.. notSooo.... All that I can think of at this point is that maybe your cache has not been cleared?
Please (please) correct me if I'm wrong ;)
Cheers!
Hey @elkuku ,
Ah, you're right, that's my browser's cache actually! I wonder if you're on Chrome too though, because it kinda should continue work well because of the browser cache. But indeed, when you manually clear the cache and do hard reload - the styles are gone. That's because the listener, IIRC
AssetMapperDevServerSubscriber, works only in dev mode. So, for prod, you indeed need to run an extra command:See more detailed information in Symfony docs: https://symfony.com/doc/current/frontend/asset_mapper.html#serving-assets-in-dev-vs-prod
Thanks for pointing it out, we will add a note about it.
Cheers!
I had the same issue!
Thanks for insisting ;-))
"Houston: no signs of life"
Start the conversation!