fbpx

Instal·lar WordPress amb Docker i MySQL 8

Instal·lar WordPress amb Docker i MySQL 8

Docker logo monocromatic

Normalment utilitzo Docker per crear aplicacions en el meu entorn de desenvolupament, especialment quan necessito executar alguns experiments o proves. Com que executar WordPress normalment implica instal·lar un servidor web, PHP i una base de dades, pot ser que sigui una tasca que requereixi molt de temps. Amb eines com Docker i Docker Compose es pot simplificar el procés de configuració. Docker és una plataforma de "contenització" que es pot utilitzar per crear i executar "contenidors".

Penseu en un contenidor Docker com una "màquina virtual lleugera". A més, amb Docker Compose és possible executar un nombre arbitrari de contenidors Docker alhora, comunicar-se i gestionar la configuració en un simple fitxer YAML.

En aquest post us mostraré alguns aspectes bàsics sobre la construcció d’una pila d'aplicacions per WordPress amb diversos contenidors mitjançant Docker compose.

Aquesta pila està formada per 3 contenidors docker:

  • WordPress 5.4.1 with php 7.4.
  • MySQL 8.0. as database
  • NGINX as front end web server.

Prerequisits:

  • Instal·leu Docker al vostre sistema.

He utilitzat Ubuntu dins de WSL2 per a Windows 10 dins del programa Insider. A més, es pot instal·lar Docker en qualsevol sistema operatiu o distribució Linux.

It’s beyond the scope of this post to explain how to install Docker or WLS2 for Windows 10. You can find more information at https://docs.docker.com/get-docker/ and https://docs.microsoft.com/en-us/windows/wsl/install-win10

Docker comes along with WSL2 backend installation as well. More information at https://docs.docker.com/docker-for-windows/wsl/.

Definició de totes les configuracions:

Comencem per crear un directori de treball:

mkdir wordpress && cd wordpress 

Next we need to create two subdirectories to store the configuration files for the database and the webserver.

mkdir conf && mkdir nginx-conf

Define configuration for Nginx

Create a new file with nano or your favorite editor:

nano nginx-conf/nginx.conf

Paste the following code into the file.

# Upstream to abstract backend connection(s) for php
upstream php {
        ## server unix:/tmp/php-cgi.socket;
        ##name of wordpress container as it appears in docker compose config file
        server wordpress:9000;
}
server {
        ## Your website name goes here.
        server_name localhost;
        ## Your only path reference.
        root /var/www/html;
        ## This should be in your http block and if it is, it's not needed here.
        index index.php;
		
	client_max_body_size 100M;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        location / {
                # This is cool because no php is touched for static content.
                # include the "?$args" part so non-default permalinks doesn't break when using query string
                try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
                include fastcgi_params;
                fastcgi_intercept_errors on;
				fastcgi_pass php;
                #The following parameter can be also included in fastcgi_params file
                fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
	
        }
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|woff2)$ {
                expires max;
                log_not_found off;
        }
}

Directives:

I included the directive client_max_body_size to prevent problems later on in case you need to upload big files in WordPress.

Define PHP Configuration

I added a uploads.ini configuration to change some php runtine configuration settings in order to increase performance and upload file size.

nano uploads.ini

Paste the following properties:

file_uploads = On
memory_limit = 256M
upload_max_filesize = 64M
post_max_size = 64M
max_execution_time = 600

Define configuration for Mysql 8

I have found some posts about issues related to Mysql 8, WordPress and docker installations.1

For this reason I configured MySQL 8 to accept connections from any IP address.

Create configuration file for MySQL 8.0.

nano conf/config-file.conf

Paste the following code into the file:

[mysqld]
bind-address	            = 0.0.0.0

Define Environment Variables

MySQL database and WordPresss application containers will need to access certain environment variables at runtime.

We set these variables in an .env file:

nano .env

The values that we will set in this file include a password for our MySQL root user, and a username and password that WordPress will use to access the database.

MYSQL_DATABASE=wordpress
MYSQL_ROOT_PASSWORD=somewordpress
MYSQL_USER=wordpress
MYSQL_PASSWORD=wordpress

Seeting up Docker Compose

The docker-compose.yml file contains the service definitions in this setup.

Open the docker-compose.yml file:

nano docker-compose.yml

Add the follogin code to Docker Compose file:

version: '3.1'

services:
  db:
    image: mysql:8.0
    container_name: db
    restart: unless-stopped
    env_file: .env
    volumes: 
      - dbdata:/var/lib/mysql
      - ./conf:/etc/mysql/conf.d
    command: '--default-authentication-plugin=mysql_native_password'
    networks:
      - app-network
  wordpress:
    depends_on: 
      - db
    image: wordpress:php7.4-fpm-alpine
    container_name: wordpress
    restart: unless-stopped
    env_file: .env
    environment:
      - WORDPRESS_DB_HOST=db:3306
      - WORDPRESS_DB_USER=wordpress
      - WORDPRESS_DB_PASSWORD=wordpress
      - WORDPRESS_DB_NAME=wordpress
      - WORDPRESS_TABLE_PREFIX=wp_
    volumes:
      - wordpress:/var/www/html
      - ./uploads.ini:/usr/local/etc/php/conf.d/uploads.ini
     networks:
      - app-network
  webserver:
    depends_on:
      - wordpress
    image: nginx:1.15.12-alpine
    container_name: webserver
    restart: unless-stopped
    ports:
      - "80:80"
    volumes:
      - wordpress:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
    networks:
      - app-network
volumes:
    wordpress:
    dbdata:
networks:
    app-network:
      driver: bridge

Create the containers with docker-compose up and the -d flag, which will run the dbwordpress, and webserver containers in the background:

docker-compose up -d

You will see output confirming that your services have been created.

You can check the status of your services using ps.

docker-compose ps

If everything was successful, your db, wordpress and webserver services will be Up.

Now you can complete your WordPress installation through the web interface. In your web browser, you can reach your site via http://localhost

Finish WordPress installation with admin settings.

Once logged in, you will have access to the WordPress administration dashboard.

Fix WordPress Docker loopback errors

You need to change WordPress address URL and Site Address if you want to fix the WordPress Docker Compose loopback error that affects cron Jobs and prevents internal file modifications 2

Use following domain names:  http://docker.for.win.localhost (windows) or http://docker.for.mac.localhost (mac).

localhost URL for mac

After that you will reach your WordPress server installation via http://docker.for.win.localhost/ (windows) or http://docker.for.mac.localhost (mac)

Conclusion

We covered how to create a wordpress installation with mysql 8 using docker.

Hope you enjoyed the article!

  1. https://github.com/docker-library/mysql/issues/275#issuecomment-292208567 []
  2. https://github.com/mjstealey/wordpress-nginx-docker/issues/8 []

Necessites ajuda amb aquest tema?

Estaré encantat d'atendre't.

Contacta per més informació: aqui 

You can give me support if you find this content is usefull!

Buy Me a Coffee

3comentaris

comments user
jayjay

Thanks for the great blog 🙂 One thing that is missing from the docker-compose.yml file is the volumes part. With this current yml file you will get some errors. Also the ‘networks’ part indentation is off.

This part should be added at the end of the file:

volumes:
dbdata:
wordpress:

Cheers!

comments user
Jordi Marti

Thank you.
I have already updated the docker.compose.yml part. 😀

comments user
piyush jain

Hi have a question how to enable letsencrypt SSL on this setup

Deixa un comentari

L'adreça electrònica no es publicarà. Els camps necessaris estan marcats amb *

caCatalan