fbpx

Instalar WordPress con Docker y MySQL 8

Instalar WordPress con Docker y MySQL 8

Docker logo monocromatic

Por lo general, uso Docker para crear aplicaciones en mi entorno de desarrollo, especialmente cuando necesito ejecutar algunos experimentos o pruebas. Debido a que ejecutar WordPress generalmente implica la instalación de un servidor web, php y una base de datos, puede ser una tarea que conlleve mucho tiempo. Con herramientas como Docker y Docker Compose, se puede simplificar el proceso de configuración. Docker es una plataforma de "contenedorización" que se puede utilizar para crear y ejecutar "contenedores".

Piense en un contenedor Docker como una "máquina virtual ligera". Además, con Docker Compose es posible ejecutar una cantidad arbitraria de contenedores Docker a la vez, comunicarse entre sí y administrar la configuración en un simple archivo YAML.

En esta publicación, voy a mostrar algunos conceptos básicos sobre la creación de una pila de aplicaciones para WordPress con varios contenedores utilizando Docker compose.

Esta pila está compuesta por 3 contenedores docker:

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

Prerequisitos:

  • Instale Docker en su sistema.

He usando Ubuntu dentro de WSL2 para Windows 10 dentro del Programa Insider. Además se puede instalar Docker en cualquier sistema operativo o distribución 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/.

Definiendo todas las configuraciones:

Empezamos creando un directorio de trabajo:

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 []

¿Necesitas ayuda con este tema?

Estaré encantado de ayudarte.

Contacta para mas información: aquí 

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

Buy Me a Coffee

3 COMENTARIOS

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

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

es_ESSpanish