Home » Devops » Быстрая установка и запуск WordPress в Docker с HTTPS

Быстрая установка и запуск WordPress в Docker с HTTPS

Некоторое время назад я писал статью про быстрое разворачивание окружения под WordPress, а так же саму установку CMS. В ней был акцент на разработку, поэтому не было простого способа запустить сайт сразу на https. Я решил пойти дальше и полностью автоматизировать установку wordpress в docker с https, чтобы можно было сразу развернуть на vps и показать в рабочем варианте. Пришлось немного доработать предыдущий вариант, добавив туда контейнер с nginx и let's encrypt.

Онлайн-курс по устройству компьютерных сетей.

На углубленном курсе "Архитектура современных компьютерных сетей" вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Wordpress with docker + https

Введение

Сразу скажу, что мной двигала лень самостоятельной настройки всего этого хозяйства. В связи с этим я искал готовые контейнеры, которым можно было бы доверять и не заботиться об их обновлении и поддержке. На долю секунды у меня возникла мысль собрать контейнеры самостоятельно, но я ее быстро отбросил :) Тогда мне было бы проще и быстрее настраивать все без докера банальным башем или ансиблом.

Для самого web сервера под wordpress нет проблем, так как docker контейнер предоставляет сама wordpress. А вот с let's encrypt возникли некоторые затруднения. Чего-то простого и легковесного не попадалось. В итоге остановился вот на этом проекте - https://docs.linuxserver.io/general/swag. Это многофункциональный web сервер, который больше заточен на проксирование запросов. Я сначала хотел использовать только его в том числе и в качестве веб сервера, но в итоге решил все же остаться на стандартном контейнере от wordpress.

Проект linuxserver достаточно известный. У них много готовых контейнеров на все случаи жизни, так что решил остановиться на нем. Немного поковырялся внутри, посмотрел, как все устроено. Когда разобрался, начал реализацию изначальной идеи - автоматизировать установку wordpress через docker сразу по https с бесплатными сертификатами от let's encrypt. Запускать все буду через docker-compose. Если у вас еще не установлен докер и композ к нему, используйте мою статью - установка docker на centos.

Подготовка конфигов

В начале подготовим конфиг nginx для проксирования запросов из контейнера с swag в wordpress. Назовем его nginx-default, так как он будет заменять дефолтный конфиг nginx.

server {
	listen 80;
	listen [::]:80;
	server_name 253197.simplecloud.ru;
	return 301 https://$host$request_uri;
}

server {
	listen 443 ssl http2 default_server;
	listen [::]:443 ssl http2 default_server;

	root /var/www/html/example;
	index index.html index.htm index.php;

	server_name 253197.simplecloud.ru;

	include /config/nginx/proxy-confs/*.subfolder.conf;

	include /config/nginx/ssl.conf;

	client_max_body_size 64M;

	location / {
		try_files $uri $uri/ /index.php?$args @app;
	}

	location @app {
		proxy_pass http://wordpress;
		proxy_set_header Host $host;
        	proxy_redirect off;
        	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        	proxy_set_header X-Forwarded-Proto https;
        	proxy_set_header X-Real-IP $remote_addr;
	}

}

Вам нужно будет в нем заменить только имя сервера - 253197.simplecloud.ru. Это dns запись vds на simplecloud, которые я обычно использую для теста. Мало того, что есть возможность почасовой аренды, так сразу же с виртуалкой идет прописанное dns имя. В итоге такие vds очень удобно использовать для тестов и временного размещения чего-либо. Рекомендую.

Далее я подготовил конфиг configure-wp.sh для установки и первоначальной настройки wordpress с помощью инструмента wp-cli, который запускается в отдельном контейнере. После того, как он все выполнит, завершает свою работу.

retries=0
while :
do
  if wp core install --url="253197.simplecloud.ru" --title="test blog" --admin_user="admin" --admin_password="pass" --admin_email="admin@sample.com"
  then
    break
  else
    retries=$((retries+1))
    echo "Couldn't connect to DB. Try - ${retries}. Sleeping 5 seconds and will retry ..."
    sleep 5
  fi
  if [ "${retries}" -eq "30" ]
  then
    echo "Couldn't connect to DB 30 times. Exiting."
    exit 1
  fi
done
wp theme install donovan --activate
wp theme uninstall twentynineteen
wp theme uninstall twentyseventeen
wp theme uninstall twentytwenty
wp plugin install wordpress-importer --activate
#wp plugin install classic-editor --activate
#wp plugin install wp-mail-smtp --activate
#wp plugin install cyr3lat --activate
#wp plugin install wordpress-seo --activate
wp plugin uninstall akismet
wp plugin uninstall hello
wp language core install ru_RU --activate

Здесь надо не забыть поменять имя сайта, а так же указать учетную запись для администратора, его email.

Так же я отдельно подготовил файл .htaccess с конфигурацией веб сервера apache, который используется в контейнере wordpress.

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

php_value memory_limit 256M
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 1000

Подготовка окончена, можно переходить к непосредственно установке wordpress через docker.

Запуск wordpress в docker с https

Теперь самое главное - готовим конфиг docker-compose для нашей магии, с помощью которой wordpress будет автоматически установлен одной командой. И не придется заморачиваться с сертификатами и всем остальным. Это все отлично подойдет для разработчиков. Самые отважные так запускают сайты в прод заказчикам. В целом, криминала в этом нет, но мне кажется на мелких проектах и одиночных vps лучше все это без докера в прод выпускать.

Вот мой финальный docker-compose.yaml.

version: '3'

services:

  swag:
    image: linuxserver/swag
    container_name: swag
    cap_add:
      - NET_ADMIN
    environment:
      - TZ=Europe/Moscow
      - URL=253197.simplecloud.ru
#      - SUBDOMAINS=www,
      - VALIDATION=http
    volumes:
      - "./nginx-default:/config/nginx/site-confs/default"
    ports:
      - 443:443
      - 80:80
    restart: unless-stopped

  mysql:
    image: mysql:8
    container_name: mysql
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: wordpress
    volumes:
      - "./mysql:/var/lib/mysql"

  wordpress:
    image: wordpress:php7.4-apache
    container_name: wordpress
    depends_on:
      - mysql
    environment:
      WORDPRESS_DB_HOST: mysql
      WORDPRESS_DB_USER: root
      WORDPRESS_DB_PASSWORD: root
      WORDPRESS_DB_NAME: wordpress
    volumes:
      - "./html:/var/www/html/"
      - "./.htaccess:/var/www/html/.htaccess"

  wp-cli:
    image: wordpress:cli
    container_name: wp-cli
    user: "33:33"
    environment:
      WORDPRESS_DB_HOST: mysql
      WORDPRESS_DB_USER: root
      WORDPRESS_DB_PASSWORD: root
      WORDPRESS_DB_NAME: wordpress
    volumes:
      - "./html:/var/www/html/"
      - "./configure-wp.sh:/opt/configure-wp.sh"
    command: "bash /opt/configure-wp.sh"

Жирным я выделил то, что вам нужно заменить на свои значения. Сохраняем конфиг и запускаем docker-compose:

# docker-compose up

Наблюдаем в консоли запуск нашего проекта на wordpress с помощью docker контейнеров. Если все в порядке, то последним вы должны у видеть примерно следующее.

Установка wordpress в docker

Успешный выпуск tls сертификата lert's encrypt будет выглядеть в логах вот так.

Настройка https в Docker

Можно сходить по адресу сайта и убедиться, что все работает.

Ваша рабочая директория со скриптами и исходниками будет выглядеть следующим образом.

  • html - исходники сайта
  • mysql - бинарные файлы базы данных

Можете все это забэкапить или положить в git, настроив исключение для директории с базой. Ее можно дампить отдельно и как-то сохранять. При желании можно в тот же git класть, если она не очень большая.

Бэкап wordpress в docker

Отдельно расскажу, как такой сайт бэкапить или куда-то переносить. Первым делом надо сделать дамп базы данных, которая живет в docker. У меня была отдельная заметка на этот счет - Backup mysql базы в docker контейнере. В нашем случае получается такая команда:

# docker exec mysql /usr/bin/mysqldump -u root --password=root wordpress | gzip -c > ~/`date +%Y-%m-%d`_wordpress.sql.gz

Исходники сайта будут лежать в директории html. Таким образом, для бэкапа всего сайта вам достаточно куда-то скопировать исходники и дамп с базой. Я рекомендую для этого использовать rsync. У меня есть отдельная статья по этой теме - настройка бэкапа с помощью rsync.

Видео

Заключение

Вот так современные технологии упрощают и ускоряют разработку и обслуживание. Сравните с тем, что надо сделать, чтобы настроить типовой веб сервер вручную - настройка веб сервера apache. А тут раз, два и все готово. И потом переносится на любую ОС с докером за минуту. Другое дело, что чтобы во всем этом разбираться, надо сначала научиться вручную все это настраивать, а потом переходить к контейнерам. Иначе они будут как черный ящик. Когда что-то сломается, останется только потыкать в него, но это не приведет к решению проблемы.

Другой вариант решения вопроса - автоматизировать все это с помощью ansible. Я пробовал что-то делать в этом направлении, но реально написать хороший плейбук занимает много времени. Если работаешь не на однотипном потоке, это не оправдывает затраты времени. С докером быстрее и проще получается.

Онлайн-курс по устройству компьютерных сетей.

На углубленном курсе "Архитектура современных компьютерных сетей" вы с нуля научитесь работать с Wireshark и «под микроскопом» изучите работу сетевых протоколов. На протяжении курса надо будет выполнить более пятидесяти лабораторных работ в Wireshark.

Помогла статья? Подписывайся на telegram канал автора

Анонсы всех статей, плюс много другой полезной и интересной информации, которая не попадает на сайт.

Автор Zerox

Владимир, системный администратор, автор сайта. Люблю настраивать сервера, изучать что-то новое, делиться знаниями, писать интересные и полезные статьи. Открыт к диалогу и сотрудничеству. Если вам интересно узнать обо мне побольше, то можете послушать интервью. Запись на моем канале - https://t.me/srv_admin/425 или на сайте в контактах.

13 комментариев

  1. На DEBAIN не работает c ошибкой вываливается вцикл

    root@debian:~# docker-compose up
    Creating network "root_default" with the default driver
    Pulling swag (linuxserver/swag:)...
    latest: Pulling from linuxserver/swag
    6f0fdad1ce92: Pull complete
    c61fe2056171: Pull complete
    604d992cfe46: Pull complete
    e4bccb8e029e: Pull complete
    59f726f113f4: Pull complete
    7e0103ab7fe6: Pull complete
    4e4429d691aa: Pull complete
    13c55a10bc72: Pull complete
    Digest: sha256:0fe779dd61b555672e5a33a70a3e36df16e4f1438e08c6775d86fbf4a52b8b2a
    Status: Downloaded newer image for linuxserver/swag:latest
    Pulling mysql (mysql:8)...
    8: Pulling from library/mysql
    767a87c58327: Extracting [=======================> ] 21.1MB/44.56MB
    767a87c58327: Extracting [=========================> ] 22.48MB/44.56MB
    9b17ad003fbc: Download complete
    410b54c19b6b: Download complete
    c6192cec9415: Download complete
    f7be351756ff: Download complete
    ae2d1ab519ee: Downloading [=======================> ] 26.47MB/56.23MB
    ae2d1ab519ee: Downloading [========================> ] 27.01MB/56.23MB
    7176b3cc6ba1: Downloading [===========================================> ] 43.19MB/50.19MB
    7176b3cc6ba1: Downloading [============================================> ] 44.21MB/50.19MB
    e935886e1025: Download complete
    ae2d1ab519ee: Downloading [========================> ] 27.55MB/56.23MB
    767a87c58327: Pull complete
    cbd6d17e71a0: Pull complete
    9b17ad003fbc: Pull complete
    410b54c19b6b: Pull complete
    c6192cec9415: Pull complete
    f7be351756ff: Pull complete
    ae2d1ab519ee: Pull complete
    119cfaa7dea0: Pull complete
    7176b3cc6ba1: Pull complete
    2eb39e909e2b: Pull complete
    e935886e1025: Pull complete
    Digest: sha256:2596158f73606ba571e1af29a9c32bec5dc021a2495e4a70d194a9b49664f4d9
    Status: Downloaded newer image for mysql:8
    Pulling wordpress (wordpress:php7.4-apache)...
    php7.4-apache: Pulling from library/wordpress
    a603fa5e3b41: Pull complete
    c428f1a49423: Pull complete
    156740b07ef8: Pull complete
    fb5a4c8af82f: Pull complete
    25f85b498fd5: Pull complete
    9b233e420ac7: Pull complete
    fe42347c4ecf: Pull complete
    d14eb2ed1e17: Pull complete
    66d98f73acb6: Pull complete
    d2c43c5efbc8: Pull complete
    ab590b48ea47: Pull complete
    80692ae2d067: Pull complete
    05e465aaa99a: Pull complete
    5e1d260f5864: Pull complete
    1f1b92fc1af4: Pull complete
    ef98b4d7e310: Pull complete
    b8532900ff77: Pull complete
    34541aa160dd: Pull complete
    179671110bb5: Pull complete
    c75ef74dd73f: Pull complete
    df68d832c77c: Pull complete
    Digest: sha256:7e46cf3373751b6d62b7a0fc3a7d6686f641a34a2a0eb18947da5375c55fd009
    Status: Downloaded newer image for wordpress:php7.4-apache
    Pulling wp-cli (wordpress:cli)...
    cli: Pulling from library/wordpress
    ef5531b6e74e: Pull complete
    0cd032c1d9bc: Pull complete
    be86720d6482: Pull complete
    03010434aa24: Pull complete
    7135a4d741b8: Pull complete
    eab8de11e4dc: Pull complete
    2ced9817301a: Pull complete
    186736c2ddd8: Pull complete
    73966b113bec: Pull complete
    ce99b761e4a9: Pull complete
    ee04395ca7c7: Pull complete
    a77342b37582: Pull complete
    a7fd88f4edd1: Pull complete
    4debb0157f92: Pull complete
    263ab354680b: Pull complete
    Digest: sha256:d55e7f92049ea2ae6ddbf564db10b26308bd419ecfc986161c99a437af9d36d3
    Status: Downloaded newer image for wordpress:cli
    Creating mysql ... done
    Creating swag ... done
    Creating wp-cli ... done
    Creating wordpress ... done
    Attaching to mysql, swag, wp-cli, wordpress
    mysql | 2023-03-09 07:27:29+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.32-1.el8 started.
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    wp-cli | Couldn't connect to DB. Try - 1. Sleeping 5 seconds and will retry ...
    wp-cli | Error: This does not seem to be a WordPress installation.
    wp-cli | Pass --path=`path/to/wordpress` or run `wp core download`.
    wp-cli | Error: This does not seem to be a WordPress installation.
    wp-cli | Pass --path=`path/to/wordpress` or run `wp core download`.
    wp-cli | Couldn't connect to DB. Try - 2. Sleeping 5 seconds and will retry ...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    wordpress | WordPress not found in /var/www/html - copying now...
    wordpress | WARNING: /var/www/html is not empty! (copying anyhow)
    wordpress | WARNING: '/var/www/html/.htaccess' exists! (not copying the WordPress version)
    wordpress | Complete! WordPress has been successfully copied to /var/www/html
    wordpress | No 'wp-config.php' found in /var/www/html, but 'WORDPRESS_...' variables supplied; copying 'wp-config-docker.php' (WORDPRESS_DB_HOST WORDPRESS_DB_NAME WORDPRESS_DB_PASSWORD WORDPRESS_DB_USER)
    mysql | 2023-03-09 07:27:36+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
    mysql | 2023-03-09 07:27:36+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.32-1.el8 started.
    mysql | 2023-03-09 07:27:37+00:00 [Note] [Entrypoint]: Initializing database files
    mysql | 2023-03-09T07:27:37.113476Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    mysql | 2023-03-09T07:27:37.245624Z 0 [Warning] [MY-010918] [Server] 'default_authentication_plugin' is deprecated and will be removed in a future release. Please use authentication_policy instead.
    mysql | 2023-03-09T07:27:37.245690Z 0 [System] [MY-013169] [Server] /usr/sbin/mysqld (mysqld 8.0.32) initializing of server in progress as process 82
    mysql | 2023-03-09T07:27:38.022064Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 3. Sleeping 5 seconds and will retry ...
    wordpress | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.21.0.5. Set the 'ServerName' directive globally to suppress this message
    wordpress | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.21.0.5. Set the 'ServerName' directive globally to suppress this message
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 4. Sleeping 5 seconds and will retry ...
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 5. Sleeping 5 seconds and will retry ...
    wordpress | [Thu Mar 09 07:27:49.090102 2023] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.54 (Debian) PHP/7.4.33 configured -- resuming normal operations
    wordpress | [Thu Mar 09 07:27:49.118354 2023] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 6. Sleeping 5 seconds and will retry ...
    mysql | 2023-03-09T07:27:55.115652Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 7. Sleeping 5 seconds and will retry ...
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    mysql | 2023-03-09T07:28:05.044561Z 6 [Warning] [MY-010453] [Server] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 8. Sleeping 5 seconds and will retry ...
    swag exited with code 1
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 9. Sleeping 5 seconds and will retry ...
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    swag exited with code 1
    wp-cli | Couldn't connect to DB. Try - 10. Sleeping 5 seconds and will retry ...
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 11. Sleeping 5 seconds and will retry ...
    mysql | 2023-03-09 07:28:25+00:00 [Note] [Entrypoint]: Database files initialized
    mysql | 2023-03-09 07:28:25+00:00 [Note] [Entrypoint]: Starting temporary server
    mysql | 2023-03-09T07:28:25.697858Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    mysql | 2023-03-09T07:28:25.699305Z 0 [Warning] [MY-010918] [Server] 'default_authentication_plugin' is deprecated and will be removed in a future release. Please use authentication_policy instead.
    mysql | 2023-03-09T07:28:25.699340Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.32) starting as process 123
    mysql | 2023-03-09T07:28:25.809649Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    swag exited with code 1
    mysql | 2023-03-09T07:28:28.856008Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 12. Sleeping 5 seconds and will retry ...
    mysql | 2023-03-09T07:28:32.969001Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
    mysql | 2023-03-09T07:28:32.969481Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
    mysql | 2023-03-09T07:28:32.981996Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
    mysql | 2023-03-09T07:28:33.437803Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Socket: /var/run/mysqld/mysqlx.sock
    mysql | 2023-03-09T07:28:33.438500Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.32' socket: '/var/run/mysqld/mysqld.sock' port: 0 MySQL Community Server - GPL.
    mysql | 2023-03-09 07:28:34+00:00 [Note] [Entrypoint]: Temporary server started.
    mysql | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 13. Sleeping 5 seconds and will retry ...
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    mysql | Warning: Unable to load '/usr/share/zoneinfo/iso3166.tab' as time zone. Skipping it.
    mysql | Warning: Unable to load '/usr/share/zoneinfo/leapseconds' as time zone. Skipping it.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 14. Sleeping 5 seconds and will retry ...
    swag exited with code 1
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 15. Sleeping 5 seconds and will retry ...
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | prog: fatal: stopping the container.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 16. Sleeping 5 seconds and will retry ...
    mysql | Warning: Unable to load '/usr/share/zoneinfo/tzdata.zi' as time zone. Skipping it.
    mysql | Warning: Unable to load '/usr/share/zoneinfo/zone.tab' as time zone. Skipping it.
    mysql | Warning: Unable to load '/usr/share/zoneinfo/zone1970.tab' as time zone. Skipping it.
    mysql | 2023-03-09 07:29:04+00:00 [Note] [Entrypoint]: Creating database wordpress
    mysql |
    mysql | 2023-03-09 07:29:04+00:00 [Note] [Entrypoint]: Stopping temporary server
    mysql | 2023-03-09T07:29:04.958837Z 11 [System] [MY-013172] [Server] Received SHUTDOWN from user root. Shutting down mysqld (Version: 8.0.32).
    swag exited with code 1
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 17. Sleeping 5 seconds and will retry ...
    mysql | 2023-03-09T07:29:08.196028Z 0 [System] [MY-010910] [Server] /usr/sbin/mysqld: Shutdown complete (mysqld 8.0.32) MySQL Community Server - GPL.
    mysql | 2023-03-09 07:29:09+00:00 [Note] [Entrypoint]: Temporary server stopped
    mysql |
    mysql | 2023-03-09 07:29:09+00:00 [Note] [Entrypoint]: MySQL init process done. Ready for start up.
    mysql |
    mysql | 2023-03-09T07:29:10.186981Z 0 [Warning] [MY-011068] [Server] The syntax '--skip-host-cache' is deprecated and will be removed in a future release. Please use SET GLOBAL host_cache_size=0 instead.
    mysql | 2023-03-09T07:29:10.215744Z 0 [Warning] [MY-010918] [Server] 'default_authentication_plugin' is deprecated and will be removed in a future release. Please use authentication_policy instead.
    mysql | 2023-03-09T07:29:10.215778Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.32) starting as process 1
    mysql | 2023-03-09T07:29:10.375850Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
    mysql | 2023-03-09T07:29:12.931095Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
    wp-cli | Error: Error establishing a database connection. This either means that the username and password information in your `wp-config.php` file is incorrect or that contact with the database server at `mysql` could not be established. This could mean your host’s database server is down.
    wp-cli | Couldn't connect to DB. Try - 18. Sleeping 5 seconds and will retry ...
    mysql | 2023-03-09T07:29:13.593828Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
    mysql | 2023-03-09T07:29:13.595416Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
    mysql | 2023-03-09T07:29:13.608075Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
    mysql | 2023-03-09T07:29:13.662601Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
    mysql | 2023-03-09T07:29:13.665471Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.32' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
    swag exited with code 1
    wp-cli | sendmail: can't connect to remote host (127.0.0.1): Connection refused
    wp-cli | Success: WordPress installed successfully.
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    wp-cli | Installing Donovan (1.9)
    wp-cli | Warning: Failed to create directory '/etc/X11/fs/.wp-cli/cache/': mkdir(): Permission denied.
    wp-cli | Downloading installation package from https://downloads.wordpress.org/theme/donovan.1.9.zip...
    swag exited with code 1
    wp-cli | Unpacking the package...
    wp-cli | Installing the theme...
    wp-cli | Theme installed successfully.
    wp-cli | Activating 'donovan'...
    wp-cli | Success: Switched to 'Donovan' theme.
    wp-cli | Success: Installed 1 of 1 themes.
    wp-cli | Warning: The 'twentynineteen' theme could not be found.
    wp-cli | Success: Theme already deleted.
    wp-cli | Warning: The 'twentyseventeen' theme could not be found.
    wp-cli | Success: Theme already deleted.
    wp-cli | Warning: The 'twentytwenty' theme could not be found.
    wp-cli | Success: Theme already deleted.
    wp-cli | Installing WordPress Importer (0.8)
    wp-cli | Warning: Failed to create directory '/etc/X11/fs/.wp-cli/cache/': mkdir(): Permission denied.
    wp-cli | Downloading installation package from https://downloads.wordpress.org/plugin/wordpress-importer.0.8.zip...
    wp-cli | Unpacking the package...
    wp-cli | Installing the plugin...
    wp-cli | Plugin installed successfully.
    wp-cli | Activating 'wordpress-importer'...
    wp-cli | Plugin 'wordpress-importer' activated.
    wp-cli | Success: Installed 1 of 1 plugins.
    wp-cli | Uninstalled and deleted 'akismet' plugin.
    wp-cli | Success: Uninstalled 1 of 1 plugins.
    wp-cli | Uninstalled and deleted 'hello' plugin.
    wp-cli | Success: Uninstalled 1 of 1 plugins.
    wp-cli | Downloading translation from https://downloads.wordpress.org/translation/core/6.1.1/ru_RU.zip...
    wp-cli | Warning: Failed to create directory '/etc/X11/fs/.wp-cli/cache/': mkdir(): Permission denied.
    wp-cli | Unpacking the update...
    wp-cli | Installing the latest version...
    wp-cli | Removing the old version of the translation...
    wp-cli | Translation updated successfully.
    wp-cli | Language 'ru_RU' installed.
    wp-cli | Success: Language activated.
    wp-cli | Success: Installed 1 of 1 languages.
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | moving to /config/nginx/site-confs/default.conf
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    wp-cli exited with code 0
    swag exited with code 1
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    swag exited with code 1
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    swag exited with code 1
    swag | [migrations] started
    swag | [migrations] 01-nginx-site-confs-default: executing...
    swag | found /config/nginx/site-confs/default
    swag | moving to /config/nginx/site-confs/default.conf
    swag | mv: cannot move '/config/nginx/site-confs/default' to '/config/nginx/site-confs/default.conf': Resource busy
    swag | [migrations] 01-nginx-site-confs-default: failed with exit code 1, contact support
    swag | s6-rc: warning: unable to start service init-migrations: command exited 1
    swag | /run/s6/basedir/scripts/rc.init: warning: s6-rc failed to properly bring all the services up! Check your logs (in /run/uncaught-logs/current if you have in-container logging) for more information.
    swag | prog: fatal: stopping the container.
    swag exited with code 1

  2. Сергей

    Владимир а есть пример этого стека для большого количество сайтов (к примеру больше 20).

    1) Как в таком случае лучше организовать структуру сайтов.
    2) Как ограничить память и cpu для контейнеров?
    3) Как рассчитать лучше сколько ресурсов необходимо для 20/50 сайтов?
    4) Один стек/контейнер для баз хватит или лучше делать для каждого сайта свой контейнер? Тоже самое если к примеру подключить redis cache, хвтает одного контейнера?
    5) Насколько удобно отправить логи каждого контейнера в ELK стек?
    6) Какой load balancer смотреть?

    Стоит в таком случае смотреть на ansible? Или docker-compose проще? Или вообще не стоит делать это через doker? :)

    Заранее спасибо

    • Для такого количества сайтов нужен совершенно другой подход. Тут все надо планировать в зависимости от рабочего процесса. Опять же, речь про dev или prod сервер идет? Для прода там и логи, и мониторинг и ресурсы, все надо планировать и строить под конкретные задачи и потребности.

      • Сергей

        Речь про prod сервер. Последние 15 лет пользовался в основном 3-мя контрольными панелями: ISP Manager, VestaCP, Plex со своими серверами. Последние 2 удобные и позволяют в принципе все делать, но время потраченное на настройку и все остальное увеличивается ( ну к примеру если надо перенести 10 доменов на новый сервер, делаешь по одному и настройки то тут, то там и все это занимает время ). Щас появились еще 2 сервера и хотелось попробовать что-то новое, docker и контейнеры и была мысль что это лучшее и проще настраивать, также все в месте + используя правильно шаблоны можно одновременно добавить логи, мониторинг везде где нужно.

        • В вашем случае нужна автоматизация, а docker сам по себе ее не дает. С ним настроек не меньше, а еще больше будет, если все делать вручную. А автоматизировать судя по всему у вас некому. Если сайты типовые, я бы их не в докер переносил на один общий веб сервер (nginx + php-fpm), а настраивал добавление новых сайтов через какую-то автоматизация, например ansible. Или на худой конец bash.

  3. petrozavodsky

    Тем лучше что эти значения никто не затрет, это не будет зависеть от настроек сервера, можно т будет в каталог сайта поросто целиком все файлы cms закидывать не парясь каждый раз с правой этого файлика.

    Это пример для композа
    volumes:
    - ./lc-php.ini:/usr/local/etc/php/conf.d/php.ini

    Файлик lc-php.in рядом с докер композ файлом внутри можно писать своим memory_limit = 256M и так далее.

    • Это на самом деле на любителя. Я работаю с разработчиками и вижу, что они чаще всего через .htaccess что-то меняют. Им так проще, понятнее, удобнее. Хотя сам я всегда параметры php сервера правлю и .htaccess вообще не использую, чтобы не привязываться к apache. Но с wordpress отдельная история. Его официальный образ для docker на apache. Плюс, я лично много раз сталкивался с тем, что не на apache у wordpress что-то глючит. Например, Elementor не работает на некоторых страницах. Так что в экосистеме wordpress .htaccess очень актуален.

  4. В чем же тогда преимущества Dockera, если по вашим словам "Когда что-то сломается, останется только потыкать в него, но это не приведет к решению проблемы.". В 90% как раз что-то случается и админы ищут для себя варианты, которые как раз устойчивы к разным поломкам и так далее... Но в целом статья хорошая. На днях буду пробовать запускать докер.

    • Преимущество, очевидно, в скорости настройки всего этого добра. Черным ящиком это будет для тех, кто не разбирается, как это внутри устроено. Например, для меня это не будет проблемой, так как я понимаю и работу докера и внутренности контейнера. Я быстро решу проблему. Посыл был в том, что мало научиться запускать что-то с помощью докера, надо еще разобраться, как это все устроено и работает.

    • petrozavodsky

      Вместо того чтоб .htaccess хакать лучше php.ini в доуере поменять

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Нажимая кнопку "Отправить комментарий" Я даю согласие на обработку персональных данных.
Используешь Telegram? Подпишись на канал автора →
This is default text for notification bar