Docker for an existing Laravel app · Part 1 of 3

Tooling8 min read

The app image and the minimum stack

A PHP image built for your app, nginx and MySQL, and a Compose file that starts them. The existing app answers from containers, with its files still owned by you.

By Abhishek Fouzdar

By the end of this part the existing app runs inside Docker: PHP in one container, nginx in another, MySQL in a third, and your editor still editing the same files in the same folder. No queue, no Vite yet. Those come in part 2, once the foundation is solid.

The one idea to hold on to

Your project folder is mounted into the containers. The code is not copied into an image; the container sees the folder on your disk, live. Edit a file, reload the browser, see the change. That is a bind mount, and nearly every decision below follows from it: who owns the files the container writes, why Composer runs inside the container on first start, why nginx can read public/ without a build step.

The folder layout

Everything Docker-related lives in one place:

docker/
├── nginx/
│   └── default.conf
└── php/
    ├── Dockerfile
    ├── entrypoint.sh
    └── php.ini
compose.yaml
.dockerignore

The app image

A Dockerfile describes the image the PHP containers run from. Create docker/php/Dockerfile:

# syntax=docker/dockerfile:1
# The `app` image: PHP-FPM with the extensions a Laravel app needs. The same image runs
# the web app, the queue worker, the scheduler and every one-off artisan command.
FROM php:8.4-fpm-alpine

# Your user id and group id on the host (see compose.yaml). Files the container writes
# into the bind-mounted project then belong to you, not to root.
ARG UID=1000
ARG GID=1000

# Runtime libraries, then the build tools needed to compile the extensions, then the
# extensions, then the build tools removed again so the image stays small.
RUN apk add --no-cache \
        icu-libs libzip libpng libjpeg-turbo freetype mysql-client git bash \
    && apk add --no-cache --virtual .build-deps \
        $PHPIZE_DEPS linux-headers icu-dev libzip-dev libpng-dev libjpeg-turbo-dev freetype-dev \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j"$(nproc)" pdo_mysql intl bcmath pcntl zip gd opcache \
    && pecl install redis \
    && docker-php-ext-enable redis \
    && apk del .build-deps

# Composer, copied from its official image rather than installed by script.
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

COPY docker/php/php.ini /usr/local/etc/php/conf.d/zz-app.ini
COPY docker/php/entrypoint.sh /usr/local/bin/app-entrypoint

# www-data exists in the base image with uid 82. Re-number it to match the host user
# so that storage/ and bootstrap/cache/ end up owned by you.
RUN apk add --no-cache shadow \
    && groupmod -o -g "${GID}" www-data \
    && usermod -o -u "${UID}" -g "${GID}" www-data \
    && apk del shadow \
    && chmod +x /usr/local/bin/app-entrypoint \
    && mkdir -p /var/www/html/vendor \
    && chown -R www-data:www-data /var/www/html

ENV COMPOSER_HOME=/tmp/composer

WORKDIR /var/www/html
USER www-data

ENTRYPOINT ["app-entrypoint"]
CMD ["php-fpm"]

Read it as five decisions.

The base image is php:8.4-fpm-alpine. The official PHP image, FPM variant because nginx will talk to it over FastCGI, Alpine variant because it is a fifth of the size of the Debian one. Pin the minor version you run in production. When you upgrade PHP, you change this one line and everyone gets the upgrade on their next build.

Extensions are compiled in, then the compilers are removed. docker-php-ext-install is the official helper; it needs build tools, so they are installed as a named group (.build-deps) and deleted at the end of the same RUN. Doing it in one RUN matters: each RUN is a layer, and a layer that installed tools and a later layer that removed them still ship the tools. The list is what a typical Laravel app needs: pdo_mysql, intl, bcmath, pcntl for the queue worker's signals, zip for Composer, gd for images, opcache, and redis from PECL for part 2. Add to it when a package asks for an extension; Composer tells you.

Composer comes from its own image. COPY --from=composer:2 takes the binary from the official Composer image. No installer script, no checksum to verify by hand.

The container's user gets your user id. This is the decision that saves the most pain. By default the PHP container would run as www-data with uid 82, and every file it writes into the bind mount, logs, compiled views, uploaded files, the cache, would appear on your host as owned by a user that does not exist, which you cannot edit or delete without sudo. The two ARG lines and the usermod call re-number www-data to match the user on the host. Compose passes your real ids in; you will see where in a moment. The mkdir -p vendor is for part 3, where a variant for macOS mounts a volume there.

It runs as www-data, not root. USER www-data near the end means PHP, Composer and every artisan command run unprivileged, like they should in production.

The entrypoint

An entrypoint runs before the container's main command. Create docker/php/entrypoint.sh:

#!/bin/sh
# Runs before php-fpm, the queue worker, the scheduler and every one-off command.
#
# The project is bind-mounted over /var/www/html, so on a clean clone the container
# starts on a tree with composer.json and no vendor/. php-fpm would survive that;
# `php artisan` would not. Install once, then get out of the way. It installs, it
# never updates: composer.lock decides the versions.
set -e

if [ -f composer.json ] && [ ! -f vendor/autoload.php ]; then
    echo "app: no vendor/autoload.php, running composer install (first start on a clean clone)" >&2
    composer install --no-interaction --prefer-dist --no-progress
fi

# The base image's own entrypoint, chained rather than replaced.
exec docker-php-entrypoint "$@"

This exists because of the bind mount. The image does not contain your vendor/ folder; the mount covers that path with whatever is on your disk. On your machine today that is a full vendor/. On a teammate's fresh clone it is nothing, and a PHP container starting on a project with no autoloader is useless. The entrypoint notices and runs composer install once. It installs, it never updates: composer.lock decides versions, here as everywhere.

The last line hands over to the base image's own entrypoint, which is what turns the default command into a running PHP-FPM. Chaining it rather than replacing it keeps everything the official image does.

php.ini

Create docker/php/php.ini:

; Development settings for the app image. Production would turn display_errors off
; and opcache.validate_timestamps off; that is a different post.
memory_limit = 512M
upload_max_filesize = 25M
post_max_size = 25M
display_errors = On
opcache.enable = 1
opcache.validate_timestamps = 1

The official image ships with no php.ini at all, so these are the few values worth setting for development. opcache.validate_timestamps = 1 is the important one: it makes OPcache check whether a file changed before using its cached version, which is what lets you edit code and see the change without restarting anything.

nginx

Create docker/nginx/default.conf:

# Serves public/ and hands PHP requests to the `app` container over the Compose network.
server {
    listen 80;
    server_name _;
    root /var/www/html/public;
    index index.php;

    charset utf-8;
    client_max_body_size 25m;

    # Never serve a dotfile, .env above all.
    location ~ /\.(?!well-known).* {
        deny all;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

This is the standard Laravel nginx config with one line that is Docker-specific: fastcgi_pass app:9000. Compose gives every service a hostname equal to its name on a private network, so nginx reaches the PHP container as app. The dotfile rule comes first so that no later rule can be talked into serving .env.

compose.yaml

Compose describes which containers to run and how they connect. Create compose.yaml in the project root:

name: app

services:
  db:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: ${DB_DATABASE:-app}
      MYSQL_USER: ${DB_USERNAME:-app}
      MYSQL_PASSWORD: ${DB_PASSWORD:-secret}
      MYSQL_ROOT_PASSWORD: ${DB_PASSWORD:-secret}
    volumes:
      - dbdata:/var/lib/mysql
    ports:
      # Published for a database GUI on the host. The app talks to db:3306 internally.
      - "127.0.0.1:${DB_HOST_PORT:-3306}:3306"
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-p${DB_PASSWORD:-secret}"]
      interval: 5s
      timeout: 5s
      retries: 20
      start_period: 20s
    restart: unless-stopped

  app:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
      args:
        UID: "${DOCKER_UID:-1000}"
        GID: "${DOCKER_GID:-1000}"
    volumes:
      - .:/var/www/html
    depends_on:
      db:
        condition: service_healthy
    # "Healthy" means the entrypoint has finished installing vendor/.
    healthcheck:
      test: ["CMD-SHELL", "test -f vendor/autoload.php"]
      interval: 3s
      timeout: 5s
      start_period: 300s
      retries: 3
    restart: unless-stopped

  web:
    image: nginx:stable-alpine
    depends_on:
      - app
    volumes:
      - .:/var/www/html:ro
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
    ports:
      - "${APP_HOST_PORT:-8080}:80"
    restart: unless-stopped

volumes:
  dbdata:

Some of this will be familiar if you have seen a Compose file before. The parts that are easy to get wrong:

${DB_DATABASE:-app} reads a variable from the .env file in the project root, with app as the fallback. Compose reads .env on its own for exactly this purpose, so the database name, user and password are written once, in the file Laravel already uses.

MySQL's data lives in a named volume, dbdata, not in the bind mount and not in the container. Named volumes survive docker compose down; only down -v deletes them. Your data is as safe as it was in a native MySQL, and bin/dev fresh in part 3 is how you deliberately throw it away.

The database port is published on 127.0.0.1 only. You can point a GUI at localhost:3306, but nothing else on your network can. The app does not use this port at all: inside the Compose network it talks to db:3306.

Healthchecks and depends_on with a condition are what make start-up reliable. Without them, Compose starts app the moment db exists, which is seconds before MySQL accepts connections, and the first request fails. With condition: service_healthy, app waits until mysqladmin ping succeeds. The app healthcheck does the same job for the entrypoint: it reports healthy only once vendor/autoload.php exists, so anything that waits on app waits for the Composer install too. start_period: 300s gives a cold install five minutes before failures count.

DOCKER_UID and DOCKER_GID are the arguments the Dockerfile uses to re-number its user. They are not in .env; part 3's script exports them from id -u and id -g so every teammate's build matches their own account. For now you will export them by hand.

nginx mounts the project read-only and the config file on top. It needs to read public/ and nothing else.

.dockerignore

Create .dockerignore:

.git
vendor
node_modules
storage/logs/*

When Docker builds the image it first sends the build context, your whole project folder, to the daemon. The image never copies the project in, so sending vendor/ and .git is pure waste, and on a large project it turns a two-second build into a minute.

.env

Point the app at the container's MySQL instead of a local one. In .env:

APP_URL=http://localhost:8080

DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=app
DB_PASSWORD=secret

DB_HOST=db is the service name, and it is the single most common thing to get wrong when moving an app into Docker: 127.0.0.1 inside the app container is the app container, where no MySQL is listening. Make the same change in .env.example, so a teammate's fresh copy starts right. If your app currently uses database for sessions, cache or queue, leave it; those tables will be migrated below and everything works. Part 2 moves them to Redis.

If your existing database has data you want to keep, export it now with your current tools and import it after the first start: docker compose exec -T db mysql -uapp -psecret app < dump.sql.

Starting it

The first build compiles PHP extensions and takes a few minutes. After that, Docker caches every layer and a restart takes seconds.

export DOCKER_UID=$(id -u) DOCKER_GID=$(id -g)
docker compose up -d --build --wait

--wait returns when every service with a healthcheck reports healthy, which means MySQL is accepting connections and vendor/ is in place. Then run the migrations inside the container:

docker compose exec app php artisan migrate
   INFO  Running migrations.

  0001_01_01_000000_create_users_table ........... DONE
  0001_01_01_000001_create_cache_table ........... DONE
  0001_01_01_000002_create_jobs_table ............ DONE

Open http://localhost:8080. The app is running from containers, on files you can still edit in place. Check the ownership claim:

ls -l storage/logs/

Everything the container wrote is owned by you.

If port 8080 or 3306 is already taken on your machine, add APP_HOST_PORT=8090 or DB_HOST_PORT=3307 to .env and run up again. Nothing inside the containers changes; only where they appear on your host does.

Checkpoint

You should have:

  • docker/php/Dockerfile, entrypoint.sh, php.ini, docker/nginx/default.conf, compose.yaml, .dockerignore;
  • DB_HOST=db in .env and .env.example;
  • the app answering on http://localhost:8080 after docker compose up -d --build --wait and a migrate;
  • files under storage/ owned by your user.

What is missing: queued jobs are not being processed, the scheduler is not running, assets are whatever was last built, and mail goes to the log. Part 2 adds all of it.

New posts by email

Get new posts by email. Nothing else, no digests, unsubscribe in one click.

Comments

Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.