We recently did a blog post on deploying Magento 2 for production. Since then we’ve refined this process in order to minimise downtime and we wanted to explain these changes in a new blog as the last one was already long enough!
The primary change that we made was to move static and DI compilation out of the live environment and into the build environment (RC) so that this work is done offline in the release candidate.There are two wrinkles to this:
The first of these issues of needing a database link is easy to solve – copy env.php into the relevant RC folder.The second issue of needing to run setup scripts before compilation is trickier, as you do not want to run these on the live database before the lengthy process of static compilation and/or code updates as you’ll end up with code and data out of sync. Instead we take a copy of the live database in these cases and run the upgrade scripts on these before static and DI compilation in RC. After rsync when we run the setup upgrade on the live server, we can use –keep-generated to ensure that our updated static and DI files are not replaced.
Here are the general steps of this updated process. There is less detail here than in the last post, so if you are trying to set this up then please check that post for reference.
No change here other than to ensure that env.php is available in app/etc on RC.
For speedy duplication we create duplicate database tables using CREATE TABLE new LIKE old and copy the data using INSERT INTO new SELECT * FROM old. Obviously this is a simplification. Our class to perform the duplication is available on github.
Depending on whether we’ve duplicated the live database we will either use the live or RC database. This is done by modifying the env.php file – easily done as it’s a PHP array definition that can be loaded in by $envData = include('env.php')
and written out by file_put_contents('env.php', "<?php\nreturn " . var_export($envData, true) . ";");
The same as before, except that we sync the pub/static files and var/generation files. A slight issue is that bundled javascript files in pub/static/_cache will be deleted and only recreated on the fly if the full page cache is cleared.
This reduces downtime from the order of 20 minutes to 20 seconds for scripts to run.That’s it! Much improved in terms of down-time, and seems solid as we’ve been using this on production for a while now.