-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.Dockerfile
383 lines (363 loc) · 18.9 KB
/
api.Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
ARG PHP_VERSION=8.3
# -----------------------------------------------------------------------------
# Base image with common dependencies for prod & dev and php & nginx installation
# -----------------------------------------------------------------------------
FROM debian:bookworm-slim AS base
# Switch shell to bash for better support
SHELL ["/bin/bash", "-e", "-u", "-x", "-o", "pipefail", "-c"]
ARG PHP_VERSION
# Fix apt warning "TERM is not set" (https://stackoverflow.com/a/35976127/4156752)
ARG DEBIAN_FRONTEND=noninteractive
# Download and cache apt packages
RUN rm -f /etc/apt/apt.conf.d/docker-clean \
&& echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' >/etc/apt/apt.conf.d/keep-cache
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
# Update system first
apt-get update -qq \
&& apt-get dist-upgrade -qq >/dev/null \
\
# apt-utils to fix "debconf: delaying package configuration, since apt-utils is not installed" but also needs "DEBIAN_FRONTEND=noninteractive"
&& apt-get -qq install \
apt-utils >/dev/null \
\
# Install additional packages
&& apt-get -qq install \
lsb-release \
bash-completion \
openssl \
ca-certificates \
curl \
gnupg \
wget \
git \
ncdu \
vim \
neovim \
nano \
# For composer to download packages
unzip \
# To run multiple processes simultaneously
supervisor \
# For the envsubst command
gettext-base \
# For cronjobs
cron \
# Required to check connectivity
default-mysql-client \
postgresql-client \
# Required for healthcheck
libfcgi-bin \
# For the 'top' command
procps \
# For the wait-for.sh which uses nc to check for server
netcat-traditional >/dev/null \
\
# Install PHP & Nginx (https://packages.sury.org/php/README.txt & https://packages.sury.org/nginx/README.txt)
&& curl --fail --silent --show-error --location --output /usr/share/keyrings/deb.sury.org-php.gpg https://packages.sury.org/php/apt.gpg \
&& echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-php.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" >/etc/apt/sources.list.d/php.list \
&& curl --fail --silent --show-error --location --output /usr/share/keyrings/deb.sury.org-nginx.gpg https://packages.sury.org/nginx/apt.gpg \
&& echo "deb [signed-by=/usr/share/keyrings/deb.sury.org-nginx.gpg] https://packages.sury.org/nginx/ $(lsb_release -sc) main" >/etc/apt/sources.list.d/nginx.list \
&& apt-get update -qq \
&& apt-get -qq install \
nginx \
brotli \
php${PHP_VERSION}-fpm \
# For connecting to databases
php${PHP_VERSION}-mysql \
php${PHP_VERSION}-pgsql \
# Phive requires
php${PHP_VERSION}-curl \
php${PHP_VERSION}-dom \
php${PHP_VERSION}-mbstring \
# Used for Symfony validators
php${PHP_VERSION}-intl \
# Used for BlurHash encoding
php${PHP_VERSION}-gd \
php${PHP_VERSION}-imagick \
# Used for Gallery download as Zip \
php${PHP_VERSION}-zip >/dev/null
ENV PHP_DIR=/etc/php/$PHP_VERSION/fpm
RUN \
# Fix missing default binaries
ln --symbolic php-fpm$PHP_VERSION /usr/sbin/php-fpm \
# By default, PHP-FPM uses the production config, which can be found in
# "/usr/lib/php/$PHP_VERSION/php.ini-production"
#&& ln --symbolic --force /usr/lib/php/$PHP_VERSION/php.ini-production "$PHP_DIR/php.ini" \
\
# Smoke tests
&& php --version \
&& php-fpm --version \
&& nginx -v \
\
&& { \
# Add custom PS1
# https://strasis.com/documentation/limelight-xe/reference/ecma-48-sgr-codes
echo 'export PS1="🐳 ${debian_chroot:+($debian_chroot)}\[\e[38;5;46m\]\u@\h\[\e[0m\]:\[\e[38;5;33m\]\w\[\e[0m\]\\$ "'; \
# Add bash auto completion
echo 'source /etc/profile.d/bash_completion.sh'; \
} >>"$HOME/.bashrc" \
\
# Create non-root user/group (1000:1000) for app and delete www-data
&& useradd --create-home --shell /bin/bash app \
&& mkdir --parents /usr/local/src/app \
# Delete the www-data user and use default 1000 (which also happens to
# match vagrant's default user to avoid permission issues)
&& find / -user 33 ! -path '/proc/*' -exec chown -h app {} \; \
&& userdel www-data \
&& { \
# Same as above (except bash completion, because it's already in the bashrc)
echo 'export PS1="🐳 ${debian_chroot:+($debian_chroot)}\[\e[38;5;46m\]\u@\h\[\e[0m\]:\[\e[38;5;33m\]\w\[\e[0m\]\\$ "'; \
} >>/home/app/.bashrc \
\
# Forward request and error logs to docker log collector
&& ln --symbolic --force /dev/stdout /var/log/nginx/access.log \
&& ln --symbolic --force /dev/stderr /var/log/nginx/error.log \
# Fix nginx package doesn't use file endings for sites
&& mv /etc/nginx/sites-available/default /etc/nginx/sites-available/default.conf \
&& rm /etc/nginx/sites-enabled/default \
&& ln --symbolic --force ../sites-available/default.conf /etc/nginx/sites-enabled/default.conf \
\
# Add healthcheck script for PHP-FPM (https://github.com/renatomefi/php-fpm-healthcheck)
&& curl --fail --silent --show-error --location --output /usr/local/bin/php-fpm-healthcheck \
https://raw.githubusercontent.com/renatomefi/php-fpm-healthcheck/master/php-fpm-healthcheck \
&& chmod +x /usr/local/bin/php-fpm-healthcheck \
\
# Add log files in /var/log (cannot be done in process running as "app" as
# folder belongs to root)
&& touch /var/log/xdebug.log \
&& chmod a+w /var/log/xdebug.log \
&& touch /var/log/cron.log \
&& chmod a+w /var/log/cron.log \
\
# Add cronjob for root to clean PHP session files every night (if env var
# CLEAR_SESSIONS_IN is set with the session files directory) user's app
# cronjobs are usually overwritten by projects
&& ( \
crontab -l; \
echo 'PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'; \
echo '0 0 * * * clear-sessions.sh 2>&1 | tee -a /var/log/cron.log'; \
) | crontab - \
\
# Setup PHP-FPM for Docker (https://github.com/docker-library/php/blob/master/8.2/bookworm/fpm/Dockerfile)
# Forward errors to stderr
&& sed -i 's/^\(error_log =\).*/\1\ \/proc\/self\/fd\/2/' "$PHP_DIR/php-fpm.conf" \
# Increase log limit to avoid e.g. breaking back traces (https://github.com/docker-library/php/pull/725#issuecomment-443540114)
&& sed -i '/^;log_limit/s/^;//' "$PHP_DIR/php-fpm.conf" \
&& sed -i 's/^\(log_limit =\).*/\1\ 8192/' "$PHP_DIR/php-fpm.conf" \
# php-fpm closes STDOUT on startup, so sending logs to /proc/self/fd/1 does
# not work. (https://bugs.php.net/bug.php?id=73886)
&& sed -i '/^;access\.log/s/^;//' "$PHP_DIR/pool.d/www.conf" \
&& sed -i 's/^\(access\.log =\).*/\1\ \/proc\/self\/fd\/2/' "$PHP_DIR/pool.d/www.conf" \
# Pass all environment variables to PHP-FPM
&& sed -i '/^;clear_env/s/^;//' "$PHP_DIR/pool.d/www.conf" \
# Ensure worker stdout and stderr are sent to the main error log.
&& sed -i '/^;catch_workers_output/s/^;//' "$PHP_DIR/pool.d/www.conf" \
&& sed -i '/^;decorate_workers_output/s/^;//' "$PHP_DIR/pool.d/www.conf" \
# Don't use daemon, supervisor needs the process to stay in foreground
&& sed -i '/^;daemonize/s/^;//' "$PHP_DIR/php-fpm.conf" \
&& sed -i 's/^\(daemonize =\).*/\1\ no/' "$PHP_DIR/php-fpm.conf" \
# Use more general path for socket
&& sed -i 's/\(listen =\).*/\1\ \/run\/php\/php-fpm.sock/' "$PHP_DIR/pool.d/www.conf" \
# Fix problem with logging to stdout (https://github.com/docker-library/php/issues/878#issuecomment-938595965)
&& sed -i '/^;fastcgi\.logging/s/^;//' "$PHP_DIR/php.ini" \
\
# Enable php fpm status page (https://github.com/renatomefi/php-fpm-healthcheck/blob/master/test/Dockerfile-buster)
&& sed -i '/^;pm.status_path/s/^;//' "$PHP_DIR/pool.d/www.conf" \
\
# Other settings
# Use new default user app for everything
&& sed -i 's/^\(user =\).*/\1\ app/' "$PHP_DIR/pool.d/www.conf" \
&& sed -i 's/^\(group =\).*/\1\ app/' "$PHP_DIR/pool.d/www.conf" \
&& sed -i 's/^\(listen\.owner =\).*/\1\ app/' "$PHP_DIR/pool.d/www.conf" \
&& sed -i 's/^\(listen\.group =\).*/\1\ app/' "$PHP_DIR/pool.d/www.conf" \
# Set memory limited to unlimited and use Docker memory limits instead
&& sed -i 's/^\(memory_limit =\).*/\1\ -1/' "$PHP_DIR/php.ini" \
# Change upload limit to a desirable value (use 0 for unlimited)
# General rule: memory_limi > post_max_size > upload_max_filesize
&& sed -i 's/^\(post_max_size =\).*/\1\ 100M/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(upload_max_filesize =\).*/\1\ 100M/' "$PHP_DIR/php.ini" \
\
# Improve performance for prod with OPcache (https://symfony.com/doc/current/performance.html)
# OPcache can compile and load classes at start-up and make them available to all requests until the server is restarted
&& sed -i '/^;opcache.preload/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(opcache.preload=\).*/\1\ \/usr\/local\/src\/app\/config\/preload.php/' "$PHP_DIR/php.ini" \
# required for opcache.preload
&& sed -i '/^;opcache.preload_user/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(opcache.preload_user=\).*/\1\ app/' "$PHP_DIR/php.ini" \
# Maximum memory that OPcache can use to store compiled PHP files (min 8, so cannot be set to unlimited)
&& sed -i '/^;opcache.memory_consumption/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(opcache.memory_consumption=\).*/\1\ 256/' "$PHP_DIR/php.ini" \
# maximum number of files that can be stored in the cache (calculate with "find")
&& sed -i '/^;opcache.max_accelerated_files/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(opcache.max_accelerated_files=\).*/\1\ 20000/' "$PHP_DIR/php.ini" \
# When a relative path is transformed into its real and absolute path, PHP
# caches the result to improve performance. Applications that open many PHP
# files, such as Symfony projects, should use at least these values:
# maximum memory allocated to store the results
&& sed -i '/^;realpath_cache_size/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(realpath_cache_size =\).*/\1\ 4096K/' "$PHP_DIR/php.ini" \
# save the results for 10 minutes (600 seconds)
&& sed -i '/^;realpath_cache_ttl/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(realpath_cache_ttl =\).*/\1\ 600/' "$PHP_DIR/php.ini" \
\
# Increase ImageMagick disk cache size to prevent
# Rotate operation failed, cache resources exhausted `/tmp/phpXXXXXX' @ error/cache.c/OpenPixelCache/4095
# https://blog.eq8.eu/til/imagemagic-cache-resources-exhausted.html
# https://github.com/ImageMagick/ImageMagick/issues/396#issuecomment-326849298
&& sed -i 's/\(<policy domain="resource" name="disk" value="\)[^"]*"/\18GiB"/' /etc/ImageMagick-6/policy.xml
COPY .docker/rootfs/common /
COPY api/.docker/rootfs /
ENV RUNTIME_ENVIRONMENT=prod \
APP_ENV=prod \
# Change composer cache dir to be outside /home/app/ (currently defaults to /home/app/.compose/cache) (https://getcomposer.org/doc/03-cli.md#composer-home)
COMPOSER_HOME=/var/cache/composer \
# Change default Symfony folders and fixed in "01_fix-file-permissions.sh"
APP_CACHE_DIR=/var/cache/app \
APP_LOG_DIR=/var/log/app
WORKDIR /usr/local/src/app
EXPOSE 80
#HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 CMD php-fpm-healthcheck && curl --fail http://localhost || exit 1
# Start supervisor (http://supervisord.org) as root
ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["supervisord", "-c", "/etc/supervisor/supervisord.conf"]
# -----------------------------------------------------------------------------
# Shared tools
# -----------------------------------------------------------------------------
FROM base AS composer
RUN \
# Install Composer (https://getcomposer.org/doc/faqs/how-to-install-composer-programmatically.md)
EXPECTED_CHECKSUM="$(php -r 'copy("https://composer.github.io/installer.sig", "php://stdout");')" \
&& php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" \
&& ACTUAL_CHECKSUM="$(php -r "echo hash_file('sha384', 'composer-setup.php');")" \
&& if [ "$EXPECTED_CHECKSUM" != "$ACTUAL_CHECKSUM" ]; then \
>&2 echo 'ERROR: Invalid installer checksum' \
&& rm composer-setup.php \
&& exit 1; \
fi \
&& php composer-setup.php \
--quiet \
--install-dir=/usr/local/bin \
--filename=composer \
&& rm composer-setup.php
# -----------------------------------------------------------------------------
# Dev image with dev tools like XDebug, Composer, etc.
# -----------------------------------------------------------------------------
FROM base AS dev
WORKDIR /
RUN --mount=type=cache,target=/var/cache/apt,sharing=locked \
--mount=type=cache,target=/var/lib/apt,sharing=locked \
# Install Symfony CLI
curl --tlsv1 --fail --silent --show-error --location https://dl.cloudsmith.io/public/symfony/stable/setup.deb.sh | bash \
&& apt-get -qq install \
symfony-cli \
php${PHP_VERSION}-xdebug >/dev/null
COPY --from=composer /usr/local/bin/composer /usr/local/bin/composer
RUN \
# Install PHP tools using Phive
wget -O phive.phar https://phar.io/releases/phive.phar \
&& wget -O phive.phar.asc https://phar.io/releases/phive.phar.asc \
&& gpg --keyserver hkps://keys.openpgp.org --recv-keys 0x9D8A98B29B2D5D79 \
&& gpg --verify phive.phar.asc phive.phar \
&& chmod +x phive.phar \
&& mv phive.phar /usr/local/bin/phive \
&& mkdir --parents /var/cache/phive \
&& phive --home /var/cache/phive --no-progress install --trust-gpg-keys A978220305CD5C32,31C7E470E2138192,E82B2FB314E9906E,C5095986493B4AA0 --target /usr/local/bin \
phpcs \
phpcbf \
php-cs-fixer \
infection \
# Install PHPStan
&& mkdir --parents /usr/local/src/phpstan \
&& COMPOSER_ALLOW_SUPERUSER=1 composer require --working-dir=/usr/local/src/phpstan phpstan/phpstan \
&& COMPOSER_ALLOW_SUPERUSER=1 composer config --working-dir=/usr/local/src/phpstan --no-plugins allow-plugins.phpstan/extension-installer true \
&& COMPOSER_ALLOW_SUPERUSER=1 composer require --working-dir=/usr/local/src/phpstan phpstan/extension-installer \
&& COMPOSER_ALLOW_SUPERUSER=1 composer require --working-dir=/usr/local/src/phpstan phpstan/phpstan-doctrine phpstan/phpstan-phpunit phpstan/phpstan-symfony phpstan/phpstan-strict-rules \
&& ln --symbolic /usr/local/src/phpstan/vendor/bin/phpstan /usr/local/bin/phpstan \
# Install Rector
&& mkdir --parents /usr/local/src/rector \
&& COMPOSER_ALLOW_SUPERUSER=1 composer require --working-dir=/usr/local/src/rector rector/rector \
&& ln --symbolic /usr/local/src/rector/vendor/bin/rector /usr/local/bin/rector \
\
# Smoke tests
&& php --version | grep 'Xdebug' \
&& composer --version \
&& symfony version \
&& phpcs --version \
&& phpcbf --version \
&& php-cs-fixer --version \
&& phpstan --version \
&& rector --version \
&& infection --version
RUN \
# Values used inside php.ini-development
sed -i 's/^\(zend.exception_ignore_args =\).*/\1\ Off/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(zend.exception_string_param_max_len =\).*/\1\ 15/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(expose_php =\).*/\1\ On/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(error_reporting =\).*/\1\ E_ALL/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(display_errors =\).*/\1\ On/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(display_startup_errors =\).*/\1\ On/' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(mysqlnd.collect_memory_statistics =\).*/\1\ On/' "$PHP_DIR/php.ini" \
\
# Setup XDebug
&& { \
echo; \
echo 'xdebug.mode = develop,coverage,debug'; \
# If enabled, Xdebug will first try to connect to the client that made
# the HTTP request. It checks the $_SERVER['HTTP_X_FORWARDED_FOR'] and
# $_SERVER['REMOTE_ADDR'] variables to find out which hostname or IP
# address to use.
echo 'xdebug.discover_client_host = true'; \
echo 'xdebug.idekey = PHPSTORM'; \
# XDebug can't write to /dev/stdout, so we read it indirectly with a
# separated supervisord process
echo 'xdebug.log = "/var/log/xdebug.log"'; \
echo 'xdebug.log_level = 3'; \
} >>"$PHP_DIR/php.ini" \
\
# Fix issue with GIT "detected dubious ownership in repository" error in
# local development due to CVE-2022-24765 (https://github.com/git/git/commit/8959555cee7ec045958f9b6dd62e541affb7e7d9)
&& git config --global --add safe.directory /usr/local/src/app \
\
# Prepare compose cache folder
&& mkdir --parents /var/cache/composer/cache \
&& chown --recursive app:app /var/cache/composer
WORKDIR /usr/local/src/app
# -----------------------------------------------------------------------------
# Prod build
# -----------------------------------------------------------------------------
FROM base AS prod-deps
COPY --from=composer /usr/local/bin/composer /usr/local/bin/composer
COPY api/composer.json api/composer.lock api/symfony.lock ./
RUN --mount=type=cache,target=/var/cache/composer/cache \
--mount=type=ssh,required=true \
# Don't use ~/.ssh/known_hosts (see https://stackoverflow.com/a/73264002/4156752)
ssh-keyscan -t ed25519 github.com >>/etc/ssh/ssh_known_hosts \
# Install composer dependencies (see https://stackoverflow.com/a/21921309/4156752)
# https://symfony.com/doc/current/performance.html#optimize-composer-autoloader
# https://getcomposer.org/doc/articles/autoloader-optimization.md \
# "--classmap-authoritative" doesn't work -> "Uncaught Error: Class "App\Kernel" not found in /usr/local/src/app/bin/console:14"
&& COMPOSER_ALLOW_SUPERUSER=1 composer install --no-dev --optimize-autoloader --no-scripts --no-interaction
FROM base AS prod
COPY --from=prod-deps /usr/local/src/app .
COPY api .
RUN \
# Install assets \
DATABASE_URL="sqlite3:///dev/null" TRUSTED_PROXIES="" bin/console assets:install \
# Further optimize php.ini for production
# maximum number of files that can be stored in the cache (calculate with "find" and add buffer for var folder)
&& sed -i "s/^\(opcache.max_accelerated_files=\).*/\1\ $(($(find /usr/local/src/app -type f -print | grep -c php) + 1000))/" "$PHP_DIR/php.ini" \
# In production servers, PHP files should never change, unless a new
# application version is deployed. However, by default OPcache checks if
# cached files have changed their contents since they were cached.
&& sed -i '/^;opcache.validate_timestamps/s/^;//' "$PHP_DIR/php.ini" \
&& sed -i 's/^\(opcache.validate_timestamps=\).*/\1\ 0/' "$PHP_DIR/php.ini" \
\
# Clean up after copying files to /usr/local/src/app
&& rm -rf \
.docker \
tests \
&& rm -f \
.env.test \
.gitignore \
phpunit.xml.dist