magenx/Magento-2-docker-configuration
Acerca de
Hardened Docker Configuration for Magento 2. Deploy production, secure, flexible and reusable docker infrastructure for Magento 2 in a matter of seconds.
Sistemas e infraestructuraCrecimiento de estrellas medido
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- +1
Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.
README.md
OriginalDocker Configuration for Magento 2
Deploy secure and flexible docker infrastructure for Magento 2 in a matter of seconds.

[!NOTE] By default the latest package versions are configured, above those recommended by Magento 2.
All images are Docker Hardened Images (dhi.io), pinned by SHA256 digest in.env.
This is a template. You are responsible for your server: permissions, upgrades, patches and security monitoring.
:world_map: How it works
HOST_PRIVATE_IP:HOST_PRIVATE_PORT (TLS terminated in front: load balancer / proxy)
│
[ varnish ] full page cache
│
[ nginx ] nginx/templates, from magenx/Magento-nginx-config
│ │
[ php-fpm ] [ imgproxy ] image resize / webp / avif
│
┌──────────────┬───────────┼────────────┬──────────────┐
[ mariadb ] [ cache ] [ session ] [ rabbitmq ] [ opensearch ]
valkey valkey
admin browser --> Cloudflare Access --tunnel--> [ cloudflared ] --> nginx:8081 Magento admin, /rabbitmq/, /mariadb/
[ adminer ] MariaDB web UI (profile adminer)
[ magento ] one-off CLI container: bin/magento, composer, n98-magerun2
[ cron ] supercronic runs bin/magento cron:run every minute
- Networks:
frontend(web, cache, search, queue) andbackend(database). MariaDB is only onbackendand published on127.0.0.1only. - Code layout: releases with a
currentsymlink, same pattern as zero-downtime deploys:/opt/BRAND/ ├── docker/ this repository + .env └── magento/ ├── releases/YYYYMMDDHHMM/ magento code (one folder per release) ├── public/current -> ../releases/YYYYMMDDHHMM └── shared/ persistent data, survives releases ├── var/ └── pub/media/ - Read-only code:
php,nginxandcronmountreleasesandpublicread-only. Only themagentoCLI container can write code.shared/varandshared/pub/mediaare writable. - User namespace remap: docker daemon runs with
userns-remap: default. Container UID65532(hardened image user) maps to host UID165532, so host files are owned by165532. - Logs: every container logs to host syslog, tagged
[ container_name ].
More details: SECURITY-AND-FOLDERS.md
:rocket: Deploy your project
Requirements
- Fresh Linux host: Debian 12/13 or Ubuntu 22/24, root access.
- Docker Hub account with a Personal Access Token (for
dhi.iohardened images). - Magento Marketplace access keys (for
repo.magento.com). - Domain name, and a load balancer / proxy in front for TLS.
Step 1. Bootstrap host with docker.sh
replace
BRANDwith your brand name, e.g.magenx. It becomes the project name, users, paths, DB name, queue vhost and search index prefix.
curl -Lo docker.sh https://raw.githubusercontent.com/magenx/Magento-2-docker-configuration/main/docker.sh && . docker.sh BRAND
curl -LO magenx.sh/docker.sh && . docker.sh BRAND
What the script does, in order:
- Asks you to agree to the terms.
- Writes
/etc/docker/daemon.jsonwith"userns-remap": "default". - Adds the official Docker apt repo, upgrades the system and installs
docker-ce,buildx,composeplugin, plusgit vim screen syslog-ng-core ufw apache2-utils acl. - Adds alias
doco='docker compose'andexport COMPOSE_ENV_FILES=.env,.env.secretsto~/.bashrc, so compose loads both env files in every shell (screen,suwithout-too), and makes~/.bash_profilesource~/.bashrcfor login shells. - Clones this repository into
/opt/BRAND/dockerand moves you there. - Copies
.env.templateto.envand.env.secrets.templateto.env.secretsand opens both invim(see Step 2). scripts/random_generator.shappends random passwords for all services, plus a random admin path and profiler key, to.env.secrets.scripts/web_directory.shcreates the/opt/BRAND/magentorelease layout, first release folder andcurrentsymlink, sets owner165532, permissions and ACL.- Tightens permissions on
/opt/BRAND/docker, sets.env.secretsto600and raises kernel key limits (/etc/sysctl.d/99-docker-maxkeys.conf).
[!WARNING]
scripts/random_generator.shdeletes everything below## generated passwords for servicesin.env.secretsand writes new values.
Do not re-run it after deployment, or your services and database credentials will no longer match.
Step 2. Edit .env and .env.secrets
vim opens both during Step 1 (:n for the next file). Settings go in .env, secrets in .env.secrets..env.secrets is in .gitignore. Keep it out of git or commit it encrypted, and back it up off the server: without CRYPT_KEY Magento cannot decrypt its stored config values.
Required values:
| Variable | What to set |
|---|---|
BRAND |
same brand name you passed to docker.sh |
DOMAIN |
shop domain, e.g. domain.com |
HOST_PRIVATE_IP / HOST_PRIVATE_PORT |
host IP:port where varnish listens (your load balancer target) |
COMPOSER_AUTH |
.env.secrets: your own repo.magento.com keys |
TUNNEL_TOKEN |
.env.secrets: Cloudflare Tunnel token for the private admin hostname, see Private admin access |
CRYPT_KEY / GRAPHQL_ID_SALT |
.env.secrets: Magento keys (set before install, keep secret) |
TIMEZONE |
e.g. Europe/Berlin |
Optional: memory sizes (VALKEY_*_SIZE, VARNISH_SIZE, OPENSEARCH_XMS/XMX), PHP_EXTENSION, PIE_MODULES, PHP 8.4 / 8.5 image block, imgproxy settings, COMPOSE_PROFILES="adminer" for the MariaDB web UI.
After Step 1 finishes, check the generated passwords at the end of .env.secrets.
Compose stops with missing, load .env.secrets if it runs without the secrets file.
Step 3. Login to hardened images registry
Create a token: https://app.docker.com/accounts/<YOUR DOCKERHUB USERNAME>/settings/personal-access-tokens
docker login dhi.io
Username: <YOUR DOCKERHUB USERNAME>
Password: <PAT>
Step 4. Build images and start containers
Run all commands from /opt/BRAND/docker:
cd /opt/BRAND/docker
doco up -d --build
doco ps
What happens on build:
- php image is built once with 3 targets:
php(php-fpm),magento(CLI + composer + n98-magerun2),cron(supercronic). PHP extensions compiled from source,lz4,igbinary,phpredisvia PIE. - nginx gets the
zstdmodule compiled and configs rendered fromnginx/templateswithenvsubst. Every server block insites-availableis enabled: the shop onnginx:80behind varnish, and the private admin vhost onnginx:8081for cloudflared. - cloudflared is the Cloudflare Tunnel client on its hardened image, see Private admin access.
- adminer (profile
adminer) is theadminertarget of the php image: php-fpm with the MySQL-only Adminer file. - varnish gets
vmod_dynamiccompiled. - opensearch gets
analysis-icuandanalysis-phoneticplugins. - valkey builds 2 targets:
cache(volatile) andsession(RDB + AOF persistence).
Watch startup, wait for all health checks to show healthy:
tail -f /var/log/syslog
doco logs -f
Step 5. Create service users
bash opensearch/create_user.sh # role + user BRAND, access to BRAND* indices
bash rabbitmq/create_user.sh # delete guest, add vhost BRAND, set permissions
Step 6. Install Magento
bash scripts/install_magento.sh
What the script does:
- Removes the
testdatabase, creates theBRANDdatabase and user in MariaDB with passwords from.env.secrets. composer create-projectofmagento/project-community-editioninto the current release (--no-install).- Adds
replacerules fromphp/config/cli/composer_replacetocomposer.jsonto drop unused modules. composer install.- Asks
Execute magento setup:install? [y/n]. Withyit installs Magento connected to mariadb, valkeysession+cache, rabbitmq and opensearch, admin useradminwith random password.
Save the admin password shown in the output. Then move the admin to the private hostname, see Magento admin URL. Until then the admin is on
https://DOMAIN/ADMIN_PATH(ADMIN_PATHis in.env.secrets) for the addresses innginx/templates/ipset/allow.confonly.
:lock: Private admin access (Cloudflare)
Magento admin, RabbitMQ management (/rabbitmq/) and Adminer (/mariadb/) on one private hostname, with no public admin path and no ipset/allow.conf addresses to keep up to date. cloudflared starts with the stack: the shop's DNS is on Cloudflare, so it is one more step there and admins need only a browser. Who may open which tool is decided by Cloudflare Access applications, listed in the App Launcher. The Zero Trust free plan covers 50 users.
cloudflared sends everything to one admin-only nginx vhost, nginx:8081 (nginx/templates/sites-available/private_admin.conf), never published on the host. Varnish is not in this path, so admin pages are never cached:
https://<private hostname>/ADMIN_PATH/ -> Magento admin (/ and paths not listed here answer 404)
https://<private hostname>/rabbitmq/ -> rabbitmq:15672 (management path_prefix, RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS)
https://<private hostname>/mariadb/ -> adminer:9000 (php-fpm, adminer profile)
The tools keep their own logins: RabbitMQ user BRAND with RABBITMQ_PASSWORD, Adminer the MariaDB user (MARIADB_USER / MARIADB_PASSWORD from .env.secrets, server mariadb). Adminer runs only with the adminer profile: the MySQL-only release of Adminer (ADMINER_VERSION, checked against ADMINER_SHA256 at build time) on the stack's own php-fpm image with pdo_mysql, target adminer of php/Dockerfile. No PostgreSQL, SQLite or other drivers, no environment in the workers, sessions on a tmpfs. Started while nginx is already running, /mariadb/ answers 502 for up to 30 seconds, until nginx resolves the new container (resolver ... valid=30s).
Cloudflare (starts with the stack)
admin browser --HTTPS--> Cloudflare edge (Access login, App Launcher) --tunnel--> cloudflared container (outbound only)
https://<private hostname> -> http://nginx:8081 Magento admin, /rabbitmq/, /mariadb/
- Image: built from
cloudflared/Dockerfileon theCLOUDFLARED_IMAGEbase, released with the other stack images. - Settings: the
TUNNEL_*variables in.env,TUNNEL_TOKENin.env.secrets. The tunnel is managed in the dashboard: one hostname tohttp://nginx:8081(the paths behind it are in this repository). The container joinsfrontend. - The hostname is in public DNS and shows up in certificate logs. Without a login accepted by Access, requests stop at Cloudflare and never reach the server: nothing on the server listens for this hostname publicly, so Access cannot be bypassed. Pick a neutral name, not
admin..
Setup, once:
Cloudflare Zero Trust: create the organization (team name) on the free plan. Login methods, under Integrations > Identity providers > Add new identity provider: One-time PIN (a code by email; new organizations do not get it automatically), or Google, Microsoft or GitHub with MFA enforced there. Admins need no Cloudflare account. Optionally create an Access group (Access controls > Access groups, e.g.
magento-admins) and use it in every policy below, so adding or removing a person is one edit.Access controls > Applications > Add an application > Self-hosted, one application per tool, each with its own Allow policy (the group, or narrower emails) and shown in the App Launcher (
https://<team>.cloudflareaccess.com):<private hostname>(whole hostname, empty path): Magento admin. It also covers/, the admin's/static/and/media/and anything not listed below. With a path here (e.g. the admin path), every other path reaches nginx without a login. App Launcher URL:https://<private hostname>/<ADMIN_PATH>/. Session duration: a working day or less.<private hostname>/rabbitmq,<private hostname>/mariadb: the tools, for fewer people if wanted. The more specific path wins.
In each application, select the login methods to offer; with only one, turn on Apply instant authentication. A one-time PIN is only sent to an email its policy includes.
Networks > Tunnels > Create a tunnel > Cloudflared. Copy the token from the docker command into
.env.secrets:
TUNNEL_TOKEN="eyJ..."
- Tunnel > Published application routes (older dashboards: Public hostnames): add the private hostname, service type HTTP, URL
nginx:8081. Add it only after the Access applications from step 2 exist. Not Networks > Routes: hostname and CIDR routes there are private network routes that only devices with the Cloudflare One client can use. Check from a machine without a login: every path must redirect to the Access login, never to a path on the hostname:
curl -sI https://<private hostname>/ | grep -i '^location'
curl -sI https://<private hostname>/anything | grep -i '^location'
- Add
adminertoCOMPOSE_PROFILESin.envfor the MariaDB UI. Build and start the containers (with the release workflow the images come from the release instead). The tunnel shows Healthy in the dashboard, the containers turnhealthy:
doco up -d --build nginx rabbitmq cloudflared adminer
- Magento admin URL
https://<private hostname>/, see Magento admin URL.
Admins:
- Sign in once at the App Launcher (
https://<team>.cloudflareaccess.com), which lists the applications each admin's policies allow, or open a tool's URL directly. - Add or remove: edit the Access group (or the emails in the policies), or the group in the login provider. Ongoing sessions: My Team > Users > Revoke.
- Magento admin:
https://<private hostname>/<ADMIN_PATH>/(/answers 404). RabbitMQ:https://<private hostname>/rabbitmq/, Adminer:/mariadb/. MariaDB from a desktop client: SSH tunnel to the published127.0.0.1:3306:ssh -L 3306:127.0.0.1:3306 user@server. - If admin pages fail on blocked XHR requests, check Security > Events for challenges on the private hostname and add a WAF skip rule for it.
[!WARNING] Anyone who can edit the tunnel in the Zero Trust dashboard can publish any service on the
frontendnetwork, OpenSearch and Valkey included. Give dashboard roles to as few people as possible, and never add a public hostname without an Access application in front of it.
Magento admin URL
Point the Magento admin to the private hostname (the trailing slash is required). After this the admin answers there only:
doco run --rm magento config:set admin/url/use_custom 1
doco run --rm magento config:set admin/url/custom https://<private hostname>/
doco run --rm magento cache:flush
- Magento also stores the custom URL as base URL of the admin store (
stores/0), so admin static files and media load from the private hostname too, no CORS. Keepweb/secure/base_static_urlandbase_media_urlempty or on{{secure_base_url}}: an absolute URL toDOMAINor a CDN breaks the admin (Knockout templates and fonts need CORS). Check:
. .env.secrets && doco exec -e MYSQL_PWD="$MARIADB_ROOT_PASSWORD" mariadb mariadb -uroot BRAND -e "SELECT scope, scope_id, path, value FROM core_config_data WHERE path LIKE 'web/%base%url' OR path LIKE 'admin/url/%'"
- Leave
nginx/templates/ipset/allow.confempty: the admin path onDOMAINthen answers 403 to everyone. - Back to the admin on
DOMAIN:config:set admin/url/use_custom 0, then run the check above. Delete thestores/0web/secure/base_urlandweb/unsecure/base_urlrows if they still hold the private hostname, flush the cache and add the addresses toipset/allow.confagain.
:gear: Daily operations
- Magento CLI, composer, n98-magerun2 (one-off
magentocontainer, removed after run):
doco run --rm magento cache:flush
doco run --rm magento setup:upgrade
doco run --rm magento composer require vendor/module
doco run --rm magento n98 --version
- Commands inside running containers:
doco exec -it php php -v
doco exec -it php top
. .env.secrets
doco exec -it cache valkey-cli -h cache -p 6380 -a "$VALKEY_PASSWORD" info
doco exec -it session valkey-cli -h session -p 6379 -a "$VALKEY_PASSWORD" ping
doco exec -it nginx nginx -t
- Credentials: all passwords are in
/opt/BRAND/docker/.env.secrets(MARIADB_ROOT_PASSWORD,MARIADB_PASSWORD,VALKEY_PASSWORD,RABBITMQ_PASSWORD,OPENSEARCH_PASSWORD,OPENSEARCH_ADMIN_PASSWORD). - Database shell:
. .env.secrets && doco exec -e MYSQL_PWD="$MARIADB_ROOT_PASSWORD" mariadb mariadb -uroot
- Import a SQL dump into the
BRANDdatabase.-Tturns off the TTY, otherwise compose stops withcannot attach stdin to a TTY-enabled container. The password goes inMYSQL_PWD:-pasks on a terminal, there is none. A dump usually drops and recreates its tables, so back up the current database first:
. .env.secrets && doco exec -T -e MYSQL_PWD="$MARIADB_ROOT_PASSWORD" mariadb mariadb -uroot BRAND < backup.sql
- Rebuild one service after config change:
doco up -d --build nginx
- Stop and remove containers (named volumes and
/opt/BRAND/magentoare kept):
doco down
:package: Build, test and release images
For a per-customer repository: images are built in GitHub Actions, pushed to ghcr.io and the server only pulls them..github/workflows/release.yml runs on every push to main:
- release-please keeps a release PR from conventional commits (
fix:patch,feat:minor,feat!:major). Merging it creates a draft release and tagvX.Y.Z. scripts/image_fingerprint.shhashes the inputs of each image: build args the Dockerfile declares (incl. base image digests), target, build context files and build secret. Images are taggedghcr.io/<owner>/BRAND-<service>:<fingerprint>. A tag that already exists is reused, only changed images are built, withdocker buildx bakefromdocker-compose.ymland a registry layer cache (:buildcache).- Scans the changed images with Trivy (
scripts/scan_images.sh, vulnerabilities only). A CRITICAL or HIGH CVE that has a fixed version fails the build, CVEs without a fix are listed in the job summary. - Starts the stack with
docker-compose.ci.yml(json-file logging, varnish and the private admin vhost on localhost), waits for all health checks, checks php extensions, composer,nginx -tandcloudflared version, then the private admin vhost:/answers 404,/rabbitmq/the RabbitMQ UI and/mariadb/the Adminer login page. Generates an SPDX SBOM of every image with Syft. - Pushes the new images and tags all 12 (
adminerincluded, whateverCOMPOSE_PROFILESsays) with the release version as well (BRAND-<service>:X.Y.Z, same digest as the fingerprint tag). Attachesdocker-compose.release.ymlwith the digests of all images andsbom.tar.gz(one SPDX file per image) to the draft release. Unchanged images keep their digest, so the server does not recreate those containers. - Publishes the release.
.github/workflows/image-scan.yml scans the images of the latest release every night for CVEs published since the release. Findings go into one open issue with label image-cve, which is updated and commented when they change and closed on a clean run.
Repository setup:
- Commit
.envwith the shop settings.nginx/templatesis in the repository: edit it there. Never commit.env.secretsunencrypted. - Variable
BUILD_IMAGES=true. Without it only the release is published, no images. - Variable
BUILD_RUNNER:ubuntu-latest(amd64, default) orubuntu-24.04-arm(arm64), same arch as the server. - Variable
BUILD_EPOCH(optional, default0): bump it to rebuild all images on the next release. The fingerprint does not see unpinned downloads during the build (apt packages, n98-magerun2). - Secrets
DHI_USER,DHI_PAT:dhi.iologin. - Secret
BUILD_SECRETS: the lines from the server.env.secretsthat are built into images:OPENSEARCH_ADMIN_PASSWORD,ADMIN_PATH,PROFILER. All other passwords in CI are throwaway values. - Settings > Actions > General: allow GitHub Actions to create pull requests (release-please).
- Settings > General > Releases: enable release immutability, so a published release and its lock file cannot change.
Deploy a release on the server (.env and .env.secrets stay on the server, docker login ghcr.io with a classic PAT with read:packages):
gh release download vX.Y.Z -p docker-compose.release.yml --clobber
doco -f docker-compose.yml -f docker-compose.release.yml pull
doco -f docker-compose.yml -f docker-compose.release.yml up -d --no-build
Roll back: download the lock file of the previous release and run the same commands.
A CVE scan fails a release or opens the image-cve issue:
- update the base image digest or the package; for unpinned apt packages bump
BUILD_EPOCH - if the fix cannot be taken yet or the package is not used at runtime, add the CVE id to
.trivyignorewith the image, the reason and a review date
Which images contain a library, e.g. after a new CVE: download the SBOMs of the release and search them:
gh release download vX.Y.Z -p sbom.tar.gz && tar -xzf sbom.tar.gz
jq -r '.packages[] | "\(.name) \(.versionInfo)"' php.spdx.json | grep -i openssl
:hammer_and_wrench: Stack components in use
Docker Hardened Images - https://hub.docker.com/hardened-images/catalog
Versions below match .env.template, images are pinned by digest and updated by Renovate.
- MariaDB 11.4 - high performing open source relational database, forked from MySQL.
- Nginx 1.31 - web server and reverse proxy, with zstd module.
- PHP 8.4 - PHP-FPM, Magento CLI with Composer 2 and n98-magerun2 (8.5 optional).
- Varnish 8 - HTTP accelerator, full page cache, with vmod_dynamic.
- OpenSearch 3 - search and analytics engine, with ICU and phonetic analysis plugins.
- Valkey 8 - key-value store, separate
cacheandsessioninstances. - RabbitMQ 4 - multi-protocol messaging broker for Magento queues.
- imgproxy 4 - fast image resizing and conversion (webp / avif) from
pub/media. - Supercronic - crontab-compatible job runner, designed for containers.
- cloudflared - Cloudflare Tunnel client, private admin access behind Cloudflare Access.
- Adminer - MariaDB web UI, MySQL-only release on the php-fpm image (profile
adminer).
Explorar proyectos relacionados
Cargando…