Постановка задачи:
Установить WordPress из готового шаблона и дампа базы данных с помощью shell-скриптов, как одного из способов/инструмента provisioning в Vagrant
1)Установка двух Ubuntu16.04 LTS серверов средствами Vagrant
2)Установка и настройка WEB-сервера (Nginx+php-fpm) (frontend-сервер) -192.168.1.91 с помощью shell-скрипта web.sh
3)Установка и настройка сервера баз данных (MySQL) (backend-сервер) – 192.168.1.92 с помощью shell-скрипта mysql.sh
Корень сайта на WEB-сервере будет создан как символьная ссылка на расшаренный каталог с шаблоном сайта с хостовой ноды, на которой установлен Vagrant(опция config.vm.synced_folder в Vagrant-файле)
Структура доступного для вирт.машин каталога на ноде имеет вид
1 |
# tree data/ | less |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
data ├── mysql | |---.my.cnf ├── nginx │ ├── default.conf │ ├── nginx.conf │ └── nginx.list ├── php │ ├── php-fpm.conf │ ├── php.ini │ └── www.conf └── template-wordpress ├── base │ └── wordpress.sql └── data ├──…….wordpress-files/directories |
Строки подключения кода к базе в WordPress в файле wp-config.php имеют вид
1 |
# cat data/template-wordpress/data/wp-config.php |
1 2 3 4 |
define('DB_NAME', 'databasename'); define('DB_USER', 'databaseuser'); define('DB_PASSWORD', 'databasepassword'); define('DB_HOST', 'localhost'); |
Файл c настройками подключения для mysql-клиента .my.cnf имеет вид
1 |
# cat data/mysql/.my.cnf |
1 2 3 |
[client] user=root password=rootpassword |
Установка Vagrant описана в отдельной статье
https://kamaok.org.ua/?p=2004
Vagrant-файл имеет вид
1 |
# nano Vagrantfile |
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 |
Vagrant.configure("2") do |config| config.vm.box = "ubuntu/xenial64" config.vm.boot_timeout = 1800 #config.ssh.username = "vagrant" #config.ssh.password = "vagrant" config.vm.communicator = "ssh" config.vm.graceful_halt_timeout = 60 config.vm.box_check_update = false config.vm.synced_folder ".", "/vagrant", disabled: true config.vm.synced_folder "./data", "/vagrant_data" # owner: "ubuntu", group: "ubuntu" config.vm.provider "virtualbox" do |vb| vb.memory = "1024" vb.cpus = "1" end config.vm.define "web", primary: true do |web| web.vm.box = "ubuntu/xenial64" web.vm.hostname = "nginx-php-fpm" web.vm.network "public_network", ip: "192.168.1.91" web.vm.provision :shell, path: "web.sh" # run: "always" end config.vm.define "db" do |db| db.vm.box = "ubuntu/xenial64" db.vm.hostname = "mysql" db.vm.network "public_network", ip: "192.168.1.92" db.vm.provision :shell, path: "mysql.sh" # run: "always" end end |
Файл web.sh имеет вид
1 |
# cat web.sh |
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 |
#!/bin/bash CP=$(which cp) MKDIR=$(which mkdir) CHMOD=$(which chmod) CHOWN=$(which chown) SUDO=$(which sudo) GREP=$(which grep) ECHO=$(which echo) TOUCH=$(which touch) SED=$(which sed) SITENAME="wordpress3.loc" ROOTPATH="/var/www" DOCUMENTROOT="$ROOTPATH/$SITENAME" MUSER="wordpressuser" MPASSWORD="wordpresspassword" MDATABASE="wordpress" MHOST="192.168.1.92" ### Update packages $SUDO apt-get update -y && $SUDO apt-get upgrade -y ### Install and configure nginx [ -f nginx_signing.key ] || $SUDO wget http://nginx.org/keys/nginx_signing.key $SUDO apt-key add nginx_signing.key $SUDO $CP /vagrant_data/nginx/nginx.list /etc/apt/sources.list.d/ $SUDO apt-get -y update $SUDO apt-get -y install nginx $SUDO $CP /etc/nginx/nginx.conf /etc/nginx/nginx.conf~ $SUDO $CP /vagrant_data/nginx/nginx.conf /etc/nginx/nginx.conf $SUDO $CP /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf~ $SUDO $CP /vagrant_data/nginx/default.conf /etc/nginx/conf.d/ $SUDO $SED -i "s/sitename/$SITENAME/g" /etc/nginx/conf.d/default.conf $SUDO [ ! -d $ROOTPATH ] && $SUDO $MKDIR -p $ROOTPATH $SUDO ln -sf /vagrant_data/template-wordpress/data $DOCUMENTROOT $SUDO $SED -i "s/databasename/$MDATABASE/g" $DOCUMENTROOT/wp-config.php $SUDO $SED -i "s/databaseuser/$MUSER/g" $DOCUMENTROOT/wp-config.php $SUDO $SED -i "s/databasepassword/$MPASSWORD/g" $DOCUMENTROOT/wp-config.php $SUDO $SED -i "s/localhost/$MHOST/g" $DOCUMENTROOT/wp-config.php $SUDO nginx -t && $SUDO systemctl restart nginx; $SUDO systemctl enable nginx ### Install and configure PHP-FPM $SUDO apt-get install -y php-mysql php-fpm $SUDO $CP /etc/php/7.0/fpm/php.ini /etc/php/7.0/fpm/php.ini~ $SUDO $CP /vagrant_data/php/php.ini /etc/php/7.0/fpm/php.ini $SUDO $CP /etc/php/7.0/fpm/php-fpm.conf /etc/php/7.0/fpm/php-fpm.conf~ $SUDO $CP /vagrant_data/php/php-fpm.conf /etc/php/7.0/fpm/php-fpm.conf $SUDO $CP /etc/php/7.0/fpm/pool.d/www.conf /etc/php/7.0/fpm/pool.d/www.conf~ $SUDO $CP /vagrant_data/php/www.conf /etc/php/7.0/fpm/pool.d/ $SUDO $CHMOD +t /var/lib/php/sessions $SUDO $TOUCH /var/log/ubuntu.log.slow $SUDO php-fpm7.0 -t && $SUDO systemctl restart php7.0-fpm; $SUDO systemctl enable php7.0-fpm ### Install MySQL-client $SUDO apt-get -y install mysql-client |
Файл mysql.sh имеет вид
1 |
# cat mysql.sh |
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 |
#!/bin/bash MUSER="wordpressuser" MPASSWORD="wordpresspassword" MDATABASE="wordpress" MROOTPASSWORD="123456789" CP=$(which cp) CHMOD=$(which chmod) CHOWN=$(which chown) SUDO=$(which sudo) GREP=$(which grep) ECHO=$(which echo) SED=$(which sed) MYCNF="/etc/mysql/mysql.conf.d/mysqld.cnf" ### update packages $SUDO apt-get update -y && $SUDO apt-get upgrade -y ### Install and configure MySQL $SUDO debconf-set-selections <<< 'mysql-server-5.7 mysql-server/root_password password rootpass' $SUDO debconf-set-selections <<< 'mysql-server-5.7 mysql-server/root_password_again password rootpass' $SUDO apt-get -y install mysql-server MYSQL=$(which mysql) $MYSQL -u root -prootpass -e "UPDATE mysql.user SET authentication_string=PASSWORD('$MROOTPASSWORD') WHERE User='root'; flush privileges;" $SUDO $CP /vagrant_data/mysql/.my.cnf /home/ubuntu/ $SUDO $SED -i "s/rootpassword/$MROOTPASSWORD/g" /home/ubuntu/.my.cnf $SUDO $CHMOD 400 /home/ubuntu/.my.cnf $SUDO $CHOWN ubuntu:ubuntu /home/ubuntu/.my.cnf $SUDO $CP /vagrant_data/mysql/.my.cnf /root/ $SUDO $SED -i "s/rootpassword/$MROOTPASSWORD/g" /root/.my.cnf $SUDO $CHMOD 400 /root/.my.cnf $SUDO $CHOWN root:root /root/.my.cnf ### The first way $SUDO /usr/bin/mysql_secure_installation << EOF n n y y y y EOF ### The second/alternative way #$MYSQL -e "DELETE FROM mysql.user WHERE User=''" #$MYSQL -e "DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1')" #$MYSQL -e "DROP DATABASE IF EXISTS test" #$MYSQL -e "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'" #$MYSQL -e "FLUSH PRIVILEGES" $SUDO $SED -i /^bind-address/s/^/#/ $MYCNF $SUDO systemctl enable mysql $SUDO systemctl restart mysql mysqlfunction () { $MYSQL -e "create database $MDATABASE" $MYSQL -e "grant all privileges on $MDATABASE.* to $MUSER@'192.168.1.%' identified by '$MPASSWORD'; flush privileges" $MYSQL $MDATABASE < /vagrant_data/template-wordpress/base/wordpress.sql } RETVAL=$($SUDO $MYSQL -Bse "show databases" | $GREP -w $MDATABASE | wc -l) if [ $RETVAL -eq "0" ] then mysqlfunction elif [ $RETVAL -eq "1" ] then $MYSQL -e "drop database $MDATABASE" mysqlfunction else $ECHO "Something went wrong" exit 127 fi |
Содержимое файлов настройки Nginx
1 |
# cat data/nginx/nginx.list |
1 2 |
deb http://nginx.org/packages/ubuntu/ xenial nginx deb-src http://nginx.org/packages/ubuntu/ xenial nginx |
1 |
# cat data/nginx/default.conf |
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 |
server { listen 80 default_server; server_name sitename www.sitename; access_log /var/log/nginx/sitename_access.log main; error_log /var/log/nginx/sitename_error.log; location / { root /var/www/sitename; try_files $uri $uri/ /index.php; location ~* ^.+\.(jpg|jpeg|gif|png|css|tgz|rar|doc|xls|exe|pdf|ppt|txt|tar|wav|bmp|rtf|js|svg|js|mp3|ogg|mpe?g|avi|zip|gz|bz2?|swf|ico|woff|ttf|eot|otf)$ { expires +30d; add_header Cache-Control "public"; } } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location ~ \.php$ { root /var/www/sitename; try_files $uri =404; fastcgi_pass unix:/var/run/php/php7.0-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location = /favicon.ico { log_not_found off; access_log off; } location = /robots.txt { access_log off; log_not_found off; } location ~ /\.ht { deny all; } location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; allow 192.168.1.0/24; deny all; } } |
1 |
# cat data/nginx/nginx.conf |
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 |
user nginx; worker_processes 1; worker_priority -5; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; use epoll; multi_accept on; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; #access_log off; sendfile off; ### There is a VirtualBox dug to sendfile which can result in corrupted or non-updating files ### https://github.com/mitchellh/vagrant/issues/351#issuecomment-1339640 tcp_nopush on; tcp_nodelay on; server_tokens off; keepalive_timeout 65; types_hash_max_size 2048; gzip on; gzip_static on; gzip_comp_level 5; gzip_min_length 1024; gzip_proxied any; gzip_vary on; gzip_types text/plain text/xml application/xml application/x-javascript text/javascript text/css text/json; gzip_disable "msie6"; #open_file_cache max=5000 inactive=20s; #open_file_cache_valid 30s; #open_file_cache_min_uses 2; #open_file_cache_errors on; fastcgi_buffer_size 128k; fastcgi_buffers 256 16k; fastcgi_busy_buffers_size 256k; fastcgi_temp_file_write_size 256k; fastcgi_connect_timeout 90; fastcgi_send_timeout 90; fastcgi_read_timeout 90; client_max_body_size 100m; client_body_buffer_size 8K; index index.html index.php index.html; include /etc/nginx/conf.d/*.conf; } |
Содержимое файлов настройки PHP-FPM
1 |
# grep -vE '^$|^\;' data/php/php-fpm.conf |
1 2 3 4 5 6 7 8 |
[global] pid = /run/php/php7.0-fpm.pid error_log = /var/log/php7.0-fpm.log emergency_restart_threshold = 10 emergency_restart_interval = 1m process_control_timeout = 10 daemonize = yes include=/etc/php/7.0/fpm/pool.d/*.conf |
1 |
# grep -vE '^$|^\;' data/php/www.conf |
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 |
[www] user = ubuntu group = ubuntu listen = /run/php/php7.0-fpm.sock listen.owner = ubuntu listen.group = ubuntu listen.mode = 0666 pm = dynamic pm.max_children = 5 pm.start_servers = 2 pm.min_spare_servers = 1 pm.max_spare_servers = 3 pm.status_path = /status ping.path = /ping ping.response = pong slowlog = /var/log/$pool.log.slow request_slowlog_timeout = 3 request_terminate_timeout = 300 catch_workers_output = yes php_admin_value[memory_limit] = 128M php_value[session.save_handler] = files php_value[session.save_path] = /var/lib/php/sessions php_admin_value[max_execution_time] = 300 php_admin_value[post_max_size] = 100M php_admin_value[upload_max_filesize] = 100M php_admin_value[max_input_time] = 600 |
Несколько полезных команд
Запуск всех вирт.машин,описанніх в файле Vagrantfile
1 |
# vagrant up |
Аналогично,но с принудительным запуском provisioner,указанного в файла Vagrantfile
1 |
# vagrant up --provisions |
Запуск/старт только web-сервера
1 |
# vagrant up web |
Запуск/старт только сервера баз данных
1 |
# vagrant up db |
Просмотр состояния всех вирт.машин или выборочных вирт.машин
1 |
# vagrant status |
1 |
# vagrant status db |
1 |
# vagrant status web |
Принудительный запуск provisioning при уже запущенной вирт.машине
1 |
# vagrant provision |
1 |
# vagrant provision web |
1 |
# vagrant provision db |
По умолчанию provisioner запускается только один раз –при создании вирт.машины
Если есть необходимость в повторном/ручном запуске provisioner при запуске/старте вирт.машин,то используем опцию provision при перезапуске вирт.машин
1 |
# vagrant reload --provision |
1 |
# vagrant reload web --provision |
1 |
# vagrant reload db --provision |