How to fix the «file_put_contents(var/cache//mage-tags/mage---ea5_MAGE) failed to open stream: Permission denied» issue on a «setup:di:compile» command on an Amazon EC2 server?

A quick (not ideal) solution:

Step 1

Run Magento 2 compilation with sudo:

rm -rf var/di var/generation && bin/magento setup:di:compile

Step 2

Restore Magento 2 filesystem ownership:

sudo chown -R www-data:www-data . 

Complete solution:

rm -rf var/di var/generation && sudo bin/magento setup:di:compile && sudo chown -R www-data:www-data .