The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

Speeding Up PHP with OPcache in Docker

Published on by

Speeding Up PHP with OPcache in Docker image

If you’re on Docker for Mac or Docker for Windows, you might see some noticeable slowness and time to the first byte (TTFB) depending on your application’s setup. One of the most important things you can do to improve performance is enabling the OPCache module (regardless of the development environment). There are other things like volume caching (if possible), but OPcache is a win that you want in any environment you’re running PHP applications.

OPcache Settings

When you enable the OPCache module, you need to consider a few things so that your configuration is development-friendly, yet, can be ready for production if you plan on using Docker in production.

Here’s the rough configuration you’ll end up with in development:

[opcache]
opcache.enable=1
; 0 means it will check on every request
; 0 is irrelevant if opcache.validate_timestamps=0 which is desirable in production
opcache.revalidate_freq=0
opcache.validate_timestamps=1
opcache.max_accelerated_files=10000
opcache.memory_consumption=192
opcache.max_wasted_percentage=10
opcache.interned_strings_buffer=16
opcache.fast_shutdown=1

Note that we’ve hard-coded these values, which isn’t very flexible between environments. We’ll come back and make it more flexible in a minute!

The most important setting for development is the opcache.validate_timestamps=1 which allows us to make changes to our code. If you’re using a Docker volume, it means that OPcache will respect file timestamps and your changes will reflect immediately. In a production environment that’s not ideal, and that’s where our dynamic configuration will come into play shortly.

You shouldn’t copy/paste these settings verbatim without understanding what they do. The configuration primarily comes from the article Best Zend OpCache Settings/Tuning/Config by Steve Corona and is an excellent resource on understanding each of these values. Another excellent resource on performance (including OPcache) is Scaling Laravel by Chris Fidao.

Copying INI Settings in the Dockerfile

Here’s a rough Dockerfile for installing the OPcache module and copying in an INI file to configure OPCache:

FROM php:7.2-apache-stretch
 
RUN docker-php-ext-install opcache
 
COPY docker/php/conf.d/opcache.ini /usr/local/etc/php/conf.d/opcache.ini
COPY . /var/www/html

I’m not showing a complete working example of a PHP application. Laravel’s document root needs to be /var/www/html/public, but I am merely trying to demonstrate setting up OPcache in this article. For a complete example you should check out my course Docker for PHP Developers.

The Dockerfile assumes the following folder structure for organizing your Docker files:

├── app
├── bootstrap
├── config
├── database
├── docker
│   └── php
│   └── conf.d
├── public
├── resources
├── routes
├── storage
├── tests
└── vendor

Note that in a real project you’d probably have a base image instead of having all this in your project, but I’m showing this so you can follow along with the OPcache-specific configuration.

Building the Dockerfile

Here’s the build command you can run to experiment with configuring OPcache:

docker build --pull -t opcache-demo -f docker/Dockerfile .
docker run --rm -it opcache-demo bash
# In a running container:
/var/www/html# php -m | grep OPcache
Zend OPcache

Flexible Configuration with Environment

We have OPcache enabled, but if we want to make this configuration flexible we can use environment variables to configure INI settings:

[opcache]
 
opcache.enable=1
opcache.revalidate_freq=0
opcache.validate_timestamps=${PHP_OPCACHE_VALIDATE_TIMESTAMPS}
opcache.max_accelerated_files=${PHP_OPCACHE_MAX_ACCELERATED_FILES}
opcache.memory_consumption=${PHP_OPCACHE_MEMORY_CONSUMPTION}
opcache.max_wasted_percentage=${PHP_OPCACHE_MAX_WASTED_PERCENTAGE}
opcache.interned_strings_buffer=16
 
opcache.fast_shutdown=1

Now that we have an environment-powered INI file, let’s provide some defaults for our project in the Dockerfile:

FROM php:7.2-apache-stretch
 
ENV PHP_OPCACHE_VALIDATE_TIMESTAMPS="0" \
PHP_OPCACHE_MAX_ACCELERATED_FILES="10000" \
PHP_OPCACHE_MEMORY_CONSUMPTION="192" \
PHP_OPCACHE_MAX_WASTED_PERCENTAGE="10"
 
RUN docker-php-ext-install opcache
 
COPY docker/php/conf.d/opcache.ini /usr/local/etc/php/conf.d/opcache.ini
COPY . /var/www/html

Note that by default we’ll disable timestamps, so we need to override this environment value in development. In this post, we’re not going to cover using Docker Compose to set environment, but this is the rough command you can run to make sure timestamps are validated in development:

# Rebuild the image first
docker build --pull -t opcache-demo -f docker/Dockerfile .
 
docker run --rm -d \
-p 8080:80 \
-e "PHP_OPCACHE_VALIDATE_TIMESTAMPS=1" \
opcache-demo

With the Apache container running in the background, you can validate that the OPcache timestamp setting is 1 by verifying in the container:

# get the container id
docker ps
docker exec -it 6002d83c6d24 bash
 
# In a running container:
/var/www/html# php -i | grep validate_timestamps
opcache.validate_timestamps => On => On

As you can see, our configuration is now powered dynamically by environment variables! In Docker, your code will be cached with OPCache by default and will not update due to timestamps validation being disabled. Please note that if you’re using Nginx + PHP-FPM, you’ll need to either ensure that clear_env = no is in your FPM pool (probably www):

[www]
clear_env = no

You can also manually add environment variables to the pool if you don’t want to keep the entire environment available to PHP.

Learn More

While the ideas presented in this article aren’t exclusive to Docker, the extra bit of help from OPcache in development is helpful, without sacrificing the ability to update your code.

If you want to learn more about developing PHP applications with Docker and PHP, including Laravel, check out my course Docker for PHP Developers.


The links included are affiliate links which means if you decide to buy Laravel News gets a little kickback to help run this site.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Generate Secure, Memorable Passphrases in PHP with PHP Passphrase image

Generate Secure, Memorable Passphrases in PHP with PHP Passphrase

Read article
FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches image

FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches

Read article
Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot image

Capture Web Page Screenshots in Laravel with Spatie's Laravel Screenshot

Read article
Nimbus: An In-Browser API Testing Playground for Laravel image

Nimbus: An In-Browser API Testing Playground for Laravel

Read article
Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout image

Laravel 12.51.0 Adds afterSending Callbacks, Validator whenFails, and MySQL Timeout

Read article
Handling Large Datasets with Pagination and Cursors in Laravel MongoDB image

Handling Large Datasets with Pagination and Cursors in Laravel MongoDB

Read article