Skip to content

Instantly share code, notes, and snippets.

@andrewwippler
Last active November 27, 2018 18:45
Show Gist options
  • Save andrewwippler/9b62322d3dff2ddd3b1890ae0a22a17c to your computer and use it in GitHub Desktop.
Save andrewwippler/9b62322d3dff2ddd3b1890ae0a22a17c to your computer and use it in GitHub Desktop.
Docker-izing WordPress for Kubernetes
#!/bin/bash
set -euo pipefail
TERM=dumb php -- <<'EOPHP'
<?php
// database might not exist, so let's try creating it (just to be safe)
$stderr = fopen('php://stderr', 'w');
// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Alternate_Port
// "hostname:port"
// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Sockets_or_Pipes
// "hostname:unix-socket-path"
list($host, $socket) = explode(':', getenv('WORDPRESS_DB_HOST'), 2);
$port = 0;
if (is_numeric($socket)) {
$port = (int) $socket;
$socket = null;
}
$user = getenv('WORDPRESS_DB_USER');
$pass = getenv('WORDPRESS_DB_PASSWORD');
$dbName = getenv('WORDPRESS_DB_NAME');
$maxTries = 10;
do {
$mysql = new mysqli($host, $user, $pass, '', $port, $socket);
if ($mysql->connect_error) {
fwrite($stderr, 'MySQL Connection Error: (' . $mysql->connect_errno . ') ' . $mysql->connect_error . "\n");
--$maxTries;
if ($maxTries <= 0) {
exit(1);
}
sleep(3);
}
} while ($mysql->connect_error);
if (!$mysql->query('CREATE DATABASE IF NOT EXISTS `' . $mysql->real_escape_string($dbName) . '`')) {
fwrite($stderr, "\n" . 'MySQL "CREATE DATABASE" Error: ' . $mysql->error . "\n");
$mysql->close();
exit(1);
}
$mysql->close();
// see if we need to copy files over
include '/var/www/html-original/wp-includes/version.php';
$dockerWPversion = $wp_version;
if (file_exists('/var/www/html/wp-includes/version.php')) {
include '/var/www/html/wp-includes/version.php';
$installedWPversion = $wp_version;
} else {
$installedWPversion = '0.0.0';
}
fwrite($stderr, "dockerWPversion: $dockerWPversion - installedWPversion: $installedWPversion\n");
if(version_compare($dockerWPversion, $installedWPversion, '>')) {
fwrite($stderr, "Installing worpress files\n");
exec('rsync -au /var/www/html-original/ /var/www/html');
}
if (filemtime('/var/www/html-original/wp-content/themes') > filemtime('/var/www/html/wp-content/themes')) {
fwrite($stderr, "Updating theme files\n");
exec('rsync -au --delete-after /var/www/html-original/wp-content/themes/ /var/www/html/wp-content/themes');
}
EOPHP
cp /tmp/wp-config.php /var/www/html/wp-config.php
chown www-data:www-data /var/www/html/wp-config.php
chmod 400 /var/www/html/wp-config.php
chown -R www-data:www-data /var/www/html
/usr/sbin/nginx -g 'daemon off;pid /run/nginx.pid;' &
exec "$@"
FROM php:7.2-fpm-alpine
# docker-entrypoint.sh dependencies
RUN apk add --no-cache \
# in theory, docker-entrypoint.sh is POSIX-compliant, but priority is a working, consistent image
bash \
sed \
rsync \
nginx
# install the PHP extensions we need
RUN set -ex; \
\
apk add --no-cache --virtual .build-deps \
libjpeg-turbo-dev \
libpng-dev \
; \
\
docker-php-ext-configure gd --with-png-dir=/usr --with-jpeg-dir=/usr; \
docker-php-ext-install gd mysqli opcache; \
\
runDeps="$( \
scanelf --needed --nobanner --recursive \
/usr/local/lib/php/extensions \
| awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \
| sort -u \
| xargs -r apk info --installed \
| sort -u \
)"; \
apk add --virtual .wordpress-phpexts-rundeps $runDeps; \
apk del .build-deps
# set recommended PHP.ini settings
# see https://secure.php.net/manual/en/opcache.installation.php
RUN { \
echo 'opcache.memory_consumption=128'; \
echo 'opcache.interned_strings_buffer=8'; \
echo 'opcache.max_accelerated_files=4000'; \
echo 'opcache.revalidate_freq=2'; \
echo 'opcache.fast_shutdown=1'; \
echo 'opcache.enable_cli=1'; \
echo 'upload_max_filesize=25M'; \
echo 'post_max_size=25M'; \
} > /usr/local/etc/php/conf.d/opcache-recommended.ini
VOLUME /var/www/html
ADD html /var/www/html-original
COPY wp-config.php /tmp/wp-config.php
COPY nginx.conf /etc/nginx/nginx.conf
COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
CMD ["php-fpm"]
user www-data;
worker_processes 1;
worker_rlimit_nofile 1024;
events {
accept_mutex on;
accept_mutex_delay 500ms;
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type text/html;
sendfile on;
send_timeout 10;
server_tokens off;
types_hash_max_size 1024;
types_hash_bucket_size 512;
server_names_hash_bucket_size 64;
server_names_hash_max_size 512;
keepalive_timeout 30;
keepalive_requests 100;
client_body_timeout 15;
lingering_timeout 5;
tcp_nodelay on;
reset_timedout_connection on;
gzip on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_disable msie6;
gzip_min_length 20;
gzip_http_version 1.1;
gzip_proxied any;
gzip_types image/png image/gif image/jpeg text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js image/svg+xml;
gzip_vary off;
client_max_body_size 25M;
client_body_buffer_size 256k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;
proxy_buffer_size 8k;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
server {
listen 80;
server_name _;
root /var/www/html;
index index.php;
error_log /var/log/nginx/localhost.error.log;
access_log /var/log/nginx/localhost.access.log;
location / {
# try to serve file directly, fallback to app.php
try_files $uri $uri/ /index.php$is_args$args;
}
gzip_vary on;
gzip_min_length 2000;
gzip_comp_level 5;
gzip_buffers 16 8k;
gzip_proxied expired no-cache no-store private auth;
gzip_http_version 1.1;
gzip_types text/plain text/css image/jpg image/jpeg application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_disable "MSIE [1-6]\.";
location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml|svg|ttf|ttc|otf|eot|woff|woff2)$ {
expires 30d;
}
location ~ ^/.+\.php(/|$) {
fastcgi_pass localhost:9000;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}
}
}
<?php
/**
* The base configuration for WordPress
*
* The wp-config.php creation script uses this file during the
* installation. You don't have to use the web site, you can
* copy this file to "wp-config.php" and fill in the values.
*
* This file contains the following configurations:
*
* * MySQL settings
* * Secret keys
* * Database table prefix
* * ABSPATH
*
* @link https://codex.wordpress.org/Editing_wp-config.php
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', getenv('WORDPRESS_DB_NAME'));
/** MySQL database username */
define('DB_USER', getenv('WORDPRESS_DB_USER'));
/** MySQL database password */
define('DB_PASSWORD', getenv('WORDPRESS_DB_PASSWORD'));
/** MySQL hostname */
define('DB_HOST', getenv('WORDPRESS_DB_HOST'));
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', '+_IYoQPA1feb2@f.+^LFf5p3[s%]$CH?&M70?`Tt$;x>k8bk|l>crKh]+WV0Nr;w');
define('SECURE_AUTH_KEY', '(jXf[b*fTJ8gt;<WU`yUeMflZ:h#ps?wYAsP8H{+Iq.+|<,P=A_=]/oy&T8{-hr]');
define('LOGGED_IN_KEY', 'VCN3Jch]O+Jg-8aK/!N!%ICYKAjqP>D.SFHNuKtSC6hHys7YYm,4hP+c2P*(Bf*{');
define('NONCE_KEY', 'L9XIj,9%!)xY2@|r}r*<)r?yEYJ%Yd9Mw0[%+%U~B*j+JxQ5Cd:>3&I@t]4|di/A');
define('AUTH_SALT', '^kcQa+9>$= _!/p%%8u0Jq>7g<R?kQa`vUD.WE7]U8TV)A%]j&f~Ge5QBf7c@#eC');
define('SECURE_AUTH_SALT', '&oWphdQ~bE.GklbCl7d!e+UAO_gs3MdyhSA);C88&cFSh6eB6.^K;0/x}St6fQ`p');
define('LOGGED_IN_SALT', 'z~cVMdgeRtUom#X=FAB%-(l$:*dIXuA%75+r|-Rm`x$D}z|+De S}-ZVbxI=!88J');
define('NONCE_SALT', 's+^|5s}Ei~3eA|]M1nmO%|+9#H*m?x+e+l*3,!R{N]NPe?S~,|%+VfLb<9Pys-sG');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each
* a unique prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*
* For information on other constants that can be used for debugging,
* visit the Codex.
*
* @link https://codex.wordpress.org/Debugging_in_WordPress
*/
define('WP_DEBUG', false);
// If we're behind a proxy server and using HTTPS, we need to alert Wordpress of that fact
// see also http://codex.wordpress.org/Administration_Over_SSL#Using_a_Reverse_Proxy
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
$_SERVER['HTTPS'] = 'on';
}
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if (!defined('ABSPATH')) {
define('ABSPATH', dirname(__FILE__) . '/');
}
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment