Despliegue en Platform.sh
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 SubscribeTengo una idea descabellada. Despleguemos este sitio de verdad.
Requisitos para el despliegue de AssetMapper
Puedes desplegar tu código como quieras... utilizando cualquier servicio o servidor web. No importa con AssetMapper. El único requisito es que tu servidor web soporte HTTP/2 para que nuestros activos -los archivos JavaScript y CSS- puedan descargarse en paralelo superrápido. HTTP/2 es la razón por la que no es tan importante que nuestros archivos no se combinen para minimizar las peticiones.
Todos los servidores web - nginx, Caddy, lo que sea - soportan HTTP/2. O podrías añadir Cloudflare o un servicio similar delante de tu sitio, que te proporciona esto gratis... junto con algunas otras ventajas.
configuración del archivo de configuración platform.sh
De todos modos, vamos a desplegar con Platform.sh, que es una "Plataforma como Servicio", lo que significa que podemos desplegar simplemente creando unos cuantos archivos de configuración. Y esta primera sección trata sobre cómo configurarlos. Una vez que hayamos terminado, hablaremos de algunos aspectos específicos del despliegue con AssetMapper.
Así que, ¡empecemos! Vamos a hacer la mayor parte de esto en la línea de comandos con el binario Symfony. Empieza ejecutando:
symfony project:init
Esto arranca unos cuantos archivos platform.sh, que puedes ver aquí..platform.app.yaml contiene instrucciones sobre cómo desplegar - como qué comandos ejecutar, qué versión de PHP utilizar, la configuración del servidor web y más. services.yaml es donde configuras los servicios que necesitas -como bases de datos, colas, etc.- yroutes.yaml configura tus dominios, y es un poco menos importante. Ah, y también puedes añadir cualquier configuración personalizada de php.ini con este archivo.
He ido registrando mis progresos a lo largo del proceso. Así que cuando ejecuto
git status
sólo muestra estos nuevos archivos. Vamos a confirmarlos y... ¡genial!
Registrando el proyecto platform.sh
Ahora que tenemos esos archivos locales, tenemos que llamar a la gente de platform.sh y decirles que queremos crear un nuevo proyecto. Lo haremos con
symfony cloud:project:create
Ya tengo algunos proyectos en Platform.sh...., lo que significa que ya tengo una organización... y ya tiene mi tarjeta de crédito. ¡Ladrones! Si es la primera vez que haces esto, tendrás que seguir unos pasos adicionales.
Dale un título a tu proyecto, selecciona una región -yo estoy utilizando "eu-5"- y luego te pregunta qué rama será tu entorno de producción. Yo estoy utilizando la rama por defecto main.
A continuación, nos pregunta si queremos establecer "Mixed Vinyl" como remoto para este repositorio. Esto es bastante guay porque expone cómo funciona platform.sh. Para desplegar con platform.sh, en realidad empujamos nuestro repositorio git a un repositorio remoto en sus servicios. Ellos lo ven, cogen el código y lo despliegan
De todos modos, voy a decir "no", pero tú puedes decir "sí". Como voy a decir "no", me verás hacerlo manualmente en un minuto - y te explicaré más sobre ello.
Por último, te pide que confirmes el precio. Estos 12 USD al mes son la tarifa de desarrollador que puedes pagar para jugar con las cosas. Será más cara cuando decidas poner tu sitio en producción de verdad. Me encanta platform.sh por lo fácil que me hace la vida, pero hay opciones más baratas.
Tardarás uno o dos minutos en configurarlo todo entre bastidores. Cuando termine... ¡ding! Obtenemos algo de información, incluido el nuevo ID del Proyecto.
Nota al margen: También hay una interfaz web en Platform.sh, así que no todo tiene que hacerse a través de la línea de comandos. Pero, ya sabes, los empollones como yo preferimos la línea de comandos.
Vincular el código local al proyecto remoto
Copia el ID del Proyecto. Llegados a este punto, tenemos algunos archivos de configuración locales -como.platform.app.yaml - y hemos creado un nuevo "proyecto" en plataforma.sh. Pero aún no están vinculados: nuestro código local no sabe que "pertenece" a este proyecto en plataforma.sh.
Para vincularlos, ejecuta
symfony project:set-remote
y pega el ID del proyecto.
Nuestro primer despliegue
¡Listo! ¿Listo para desplegar? Hazlo con:
symfony deploy
Actualmente estamos en la rama "principal", por lo que se está desplegando a, básicamente, nuestra máquina de "producción", lo que se llama un entorno. Una de las partes más interesantes de platform.sh es que desplegarás tu rama main en el entorno de "producción", pero también puedes desplegar otras ramas git en otros entornos platform.sh, en los que puedes pensar como otros servidores platform.sh.
De todos modos, como he mencionado, entre bastidores, este comando es sólo un atajo paragit push nuestra rama a un remoto git en los servidores platform.sh. Y al hacerlo, ¡se inicia el despliegue!
Oooh, esto parece elegante y friki. Aquí hay un montón de detalles, incluida una advertencia sobre el uso de una versión antigua de Composer. Lo arreglaremos en un minuto. Aquí abajo, vemos que se está ejecutando symfony composer install y realizando algunos otros pasos: todas las cosas básicas que necesitas para desplegar cualquier aplicación Symfony.
En la parte inferior, nos da un certificado SSL, y si seguimos desplazándonos... oooh, ¡tenemos un mensaje sobre un error en la base de datos! Ignóralo por ahora porque... cuando termina, ¡nos da una URL!
Como no hemos configurado ningún dominio para el sitio, nos da una URL temporal. Cópiala, gira y... ¡nuestro sitio está vivo! No tiene ningún estilo... ya que no hemos hablado de AssetMapper, ¡pero al menos funciona!
¿Pero cómo? ¿Cómo ha sabido ejecutar composer install y esas otras cosas? ¿Y la advertencia de Composer y el error de la base de datos? Vamos a profundizar en todo eso a continuación.
17 Comments
Hi
I'm trying to run this chapter from the project root:
symfony cloud:project:create
but I get the following error:
Downloading Platform.sh CLI version 5.2.0 0% |
and then:
executable file not found in %PATH%
Hey @giorgiocba ,
Are you on Windows OS? Hm, instead of dealing with the ucsto PATH config it might be so that you need to install the Platform.sh CLI in an official way first: https://docs.platform.sh/administration/cli.html . I bet if you get that installed properly first, then
symfony cloud:project:createalso should work well for you.But I would recommend you using WSL with a native Linux installation, then such commands should work much stable. I've never executed those on Windows, so it's hard to tell what else you can do.
I hope that helps!
Cheers!
Thank you very much for your suggestion. I'm actually running Windows 10, but I have WSL installed. I'll try the deployment again now.
Yeah, on WSL it should do the installation of the Platform.sh CLI in the background without problems or needed changes.
Cheers!
Hi all and thank your for pointing me to Platform.sh. I'm currently scouting it and (my own mistakes aside) it's really as simple as in the video (even without either the Symfony CLI or the Platform CLI!).
But what bugs me right now is the time it takes to build webpack stuff. Nearly on every new commit, (aside from pure platform.sh configuration) the whole build process is executed, even when there are no changes to the JS. Is there any way to cache the build, maybe by using a mount? Right now (in the free trial dev tier) a deployment takes about five minutes or so (which gets annoying when playing around with environment variables). I'm using the standard symfony build hook.
Hey @Manuel-B!
Sorry for my slow reply!
You should try Asset Mapper ;). But to actually answer your question, the last time I asked this, no, there wasn't a built-in "build cache". But, it would be worth asking them again via support or on their Slack channel.
I agree with you that the Webpack builds on deploy can be annoying (and funnily enough, I know that platform.sh doesn't like them either - it takes resources, so everyone would be better off if they were cached). I think, to accomplish this, you'd need to write something by hand :/. There is a concept of mounts, which are directories that are shared across deploys. So, in theory, you could create some sort of a checksum of the
assets/directory and thepackage-lock.jsonand use that as your own personal "cache" key - e.g. looking for/some/directory/cached_assets/{key}. And if it's present, copying that topublic/assets/and skipping Encore. Else, build Encore then copy into the cached dir.Unfortunate that there is, I believe, nothing built-in. But it does seem possible :).
Cheers!
Hi Ryan!
Thank you for sharing your ideas with me, they have sent me on an interesting journey of how to build a JS build cache and dash. Yet another learning experience for me. :)
In the end, my trials unfortunately failed, because the mounts are not available during build time. I'll keep digging (and asking) and I'll share my solution here, if I find one.
That being said, switching to Asset Mapper is already on our todo, it's just a matter of time. :)
The answer is quite simple, now that I know about it. Thanks to Chad from Platform.sh for pointing me to the solution!
There is variable called "PLATFORM_CACHE_DIR" that is available during build time for all your environments (see list of available variables). And that just does the trick. :)
This is fantastic! I didn't know about
PLATFORM_CACHE_DIR. I think we may use it also, just to speed up the build part of the deploy. Super cool!Hi all, I've an old symfony 3.4 project that I would like to rewrite with the recent symfony 6.4, but this used the 'smart admin' theme which used dynamic loading via ajax of contents, with the window.location library and use of hashes. Do you think the hotwired system could be a valid substitute?
Hey @pasquale_pellicani!
Sorry for the slow reply - holidays!
Hmm. I want to say yes - but I'm not familiar with this "smart admin" theme system. But, generally-speaking, that does sound a lot like what Turbo offers: changing the URL on click, ability to AJAX-load contents.... it's all there.
Anyway, that's a weak answer - so let me know if I can offer more details :).
Cheers and happy 2024!
Sure, I take this opportunity to ask another question, but is this topic of the turbo and the hotwire very new ? I have had to search around for information or even pre-made templates but without success. Thank you
Hey again!
Fortunately, no. Both Turbo and Stimulus are about 10 (yes 10!) years old. Though the most recent version of both was released 2-3 years ago, and that's when the Symfony world starting using it. It also started to grow more popular and get more features around then.
This is an interesting statement. There are many pre-made Stimulus controllers - e.g. - https://www.stimulus-components.com/ - but no central place to find them... and no place to really find pre-made HTML markup + Stimulus controllers. Only moments ago, I was chatting about this with someone else - https://symfonycasts.com/screencast/last-stack/tailwind#comment-31337 - I would be interested what you think about my idea at the end.
Cheers!
thank you very much for the answers, at this point the question comes naturally, why choose stimulus/turbo and not react or vue js? I would like to understand the pros and cons between the two choices. ^_^
Hey Pasquale,
Choosing between Stimulus/Turbo and frontend frameworks such as React or Vue.js depends on the type of application you're building, the complexity of the features, and your personal preferences among other factors. Here're some ideas that I believe will help you to understand the diff:
Nature of the application: If you plan on building a Single Page Application (SPA), React or Vue might be the go-to choice as they are specifically designed to create rich interactive user interfaces with complex state handling. They allow you to return JSON from your server and build HTML 100% in JavaScript. On the other hand, if you prefer apps that primarily returns HTML from the server, Stimulus and Turbo might be a better option.
Use of existing technologies and best practices: Another reason to choose Stimulus/Turbo is if you have a preference for certain backend technologies or wish to make use of existing tools and best practices. The context mentions liking PHP, Symfony, and Twig and points out the various tools Symfony provides, like form handling and CSRF protection. If you've been building traditional server-rendered apps, then there are a plethora of tools you're familiar with that can speed up your development process.
Avoiding Full Page Refreshes: Stimulus and Turbo give you the option to create a SPA-like experience by avoiding full page refreshes without having to create an actual SPA. Turbo allows your applications to load every link click and form submit via Ajax, giving fluidity to the user experience.
Complex Features: React and Vue.js still have a place even if your application primarily returns HTML from the server and use Stimulus. If you have a particularly complex feature or widget to build on your site, React or Vue might just be the best tools for the job. They do well when complex interactivity and state management comes into play, and those components can fit perfectly into Stimulus.
Ultimately, the choice depends on your project requirements, the kind of user experience you're intending to deliver, where you want to handle most of your app’s logic (client side or server side), and personal preference.
You should add the +100 thumb below, it was the answer I was looking for, thank you all so much for the precious info ^_^
Hey Pasquale,
I'm happy to hear that comment was useful to you. I highlighted that comment, hope it will be useful for other users too :)
Cheers!
"Houston: no signs of life"
Start the conversation!