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
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Sort Elements with the Alpine.js Sort Plugin image

Sort Elements with the Alpine.js Sort Plugin

Read article
Anonymous Event Broadcasting in Laravel 11.5 image

Anonymous Event Broadcasting in Laravel 11.5

Read article
Microsoft Clarity Integration for Laravel image

Microsoft Clarity Integration for Laravel

Read article
Apply Dynamic Filters to Eloquent Models with the Filterable Package image

Apply Dynamic Filters to Eloquent Models with the Filterable Package

Read article
Property Hooks Get Closer to Becoming a Reality in PHP 8.4 image

Property Hooks Get Closer to Becoming a Reality in PHP 8.4

Read article
Asserting Exceptions in Laravel Tests image

Asserting Exceptions in Laravel Tests

Read article