如何使用Docker Compose安装WordPress

介绍 (Introduction)

WordPress is a free and open-source Content Management System (CMS) built on a MySQL database with PHP processing. Thanks to its extensible plugin architecture and templating system, and the fact that most of its administration can be done through the web interface, WordPress is a popular choice when creating different types of websites, from blogs to product pages to eCommerce sites.

WordPress是一个免费的开放源代码内容管理系统(CMS),建立在具有PHP处理功能的MySQL数据库上。 凭借其可扩展的插件体系结构和模板系统,以及其大部分管理都可以通过Web界面完成的事实,当创建从博客到产品页面再到电子商务网站的各种类型的网站时,WordPress是一种流行的选择。

Running WordPress typically involves installing a LAMP (Linux, Apache, MySQL, and PHP) or LEMP (Linux, Nginx, MySQL, and PHP) stack, which can be time-consuming. However, by using tools like Docker and Docker Compose, you can simplify the process of setting up your preferred stack and installing WordPress. Instead of installing individual components by hand, you can use images, which standardize things like libraries, configuration files, and environment variables, and run these images in containers, isolated processes that run on a shared operating system. Additionally, by using Compose, you can coordinate multiple containers — for example, an application and database — to communicate with one another.

运行WordPress通常涉及安装LAMP (Linux,Apache,MySQL和PHP)或LEMP (Linux,Nginx,MySQL和PHP)堆栈,这很耗时。 但是,通过使用DockerDocker Compose之类的工具,您可以简化设置首选堆栈和安装WordPress的过程。 您可以使用images来标准化诸如库,配置文件和环境变量之类的图像 ,而不是手动安装单个组件,并在容器中运行这些图像,这些容器是在共享操作系统上运行的独立进程。 此外,通过使用Compose,您可以协调多个容器(例如,一个应用程序和数据库)以相互通信。

In this tutorial, you will build a multi-container WordPress installation. Your containers will include a MySQL database, an Nginx web server, and WordPress itself. You will also secure your installation by obtaining TLS/SSL certificates with Let’s Encrypt for the domain you want associated with your site. Finally, you will set up a cron job to renew your certificates so that your domain remains secure.

在本教程中,您将构建多容器WordPress安装。 您的容器将包括MySQL数据库,Nginx Web服务器和WordPress本身。 您还可以通过“加密”获取要与站点关联的域的TLS / SSL证书来保护安装。 最后,您将设置cron作业来续订证书,以便您的域保持安全。

先决条件 (Prerequisites)

To follow this tutorial, you will need:

要遵循本教程,您将需要:

  • A server running Ubuntu 18.04, along with a non-root user with sudo privileges and an active firewall. For guidance on how to set these up, please see this Initial Server Setup guide.

    运行Ubuntu 18.04的服务器,以及具有sudo特权和活动防火墙的非root用户。 有关如何进行设置的指导,请参阅此初始服务器设置指南

  • Docker installed on your server, following Steps 1 and 2 of How To Install and Use Docker on Ubuntu 18.04.

    遵循如何在Ubuntu 18.04上安装和使用Docker的步骤1和2,在您的服务器上安装Docker

  • Docker Compose installed on your server, following Step 1 of How To Install Docker Compose on Ubuntu 18.04.

    遵循如何在Ubuntu 18.04上安装Docker Compose的步骤1,在您的服务器上安装Docker Compose

  • A registered domain name. This tutorial will use example.com throughout. You can get one for free at Freenom, or use the domain registrar of your choice.

    注册域名。 本教程将始终使用example.com 。 您可以从Freenom免费获得一个,或使用您选择的域名注册商。

  • Both of the following DNS records set up for your server. You can follow this introduction to DigitalOcean DNS for details on how to add them to a DigitalOcean account, if that’s what you’re using:

    为服务器设置了以下两个DNS记录。 您可以按照DigitalOcean DNS简介进行操作,以获取有关如何将其添加到DigitalOcean帐户的详细信息,如果您正在使用的话:

    • An A record with example.com pointing to your server’s public IP address.

      包含example.com的A记录,指向您服务器的公共IP地址。

    • An A record with www.example.com pointing to your server’s public IP address.

      www. example.com的A记录www. example.com www. example.com指向您服务器的公共IP地址。

步骤1 —定义Web服务器配置 (Step 1 — Defining the Web Server Configuration)

Before running any containers, our first step will be to define the configuration for our Nginx web server. Our configuration file will include some WordPress-specific location blocks, along with a location block to direct Let’s Encrypt verification requests to the Certbot client for automated certificate renewals.

在运行任何容器之前,我们的第一步将是为Nginx Web服务器定义配置。 我们的配置文件将包括一些特定于WordPress的位置块,以及将“我们加密”验证请求定向到Certbot客户端以进行自动证书更新的位置块。

First, create a project directory for your WordPress setup called wordpress and navigate to it:

首先,为您的WordPress设置创建一个名为wordpress的项目目录,然后导航至该目录:

  • mkdir wordpress && cd wordpress

    mkdir wordpress && cd wordpress

Next, make a directory for the configuration file:

接下来,为配置文件创建目录:

  • mkdir nginx-conf

    mkdir nginx-conf

Open the file with nano or your favorite editor:

使用nano或您喜欢的编辑器打开文件:

  • nano nginx-conf/nginx.conf

    纳米nginx-conf / nginx.conf

In this file, we will add a server block with directives for our server name and document root, and location blocks to direct the Certbot client’s request for certificates, PHP processing, and static asset requests.

在此文件中,我们将添加一个服务器块,其中包含用于我们的服务器名称和文档根的指令,以及用于指示Certbot客户端对证书,PHP处理和静态资产请求的指令的位置块。

Paste the following code into the file. Be sure to replace example.com with your own domain name:

将以下代码粘贴到文件中。 确保将example.com替换为您自己的域名:

~/wordpress/nginx-conf/nginx.conf
〜/ wordpress / nginx-conf / nginx.conf
server {
        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;

        index index.php index.html index.htm;

        root /var/www/html;

        location ~ /.well-known/acme-challenge {
                allow all;
                root /var/www/html;
        }

        location / {
                try_files $uri $uri/ /index.php$is_args$args;
        }

        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass wordpress:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_path_info;
        }

        location ~ /\.ht {
                deny all;
        }

        location = /favicon.ico { 
                log_not_found off; access_log off; 
        }
        location = /robots.txt { 
                log_not_found off; access_log off; allow all; 
        }
        location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
                expires max;
                log_not_found off;
        }
}

Our server block includes the following information:

我们的服务器块包含以下信息:

Directives:

指令:

  • listen: This tells Nginx to listen on port 80, which will allow us to use Certbot’s webroot plugin for our certificate requests. Note that we are not including port 443 yet — we will update our configuration to include SSL once we have successfully obtained our certificates.

    listen :这告诉Nginx监听端口80 ,这将使我们能够将Certbot的webroot插件用于我们的证书请求。 请注意,我们尚不包括端口443成功获得证书后,我们将更新配置以包括SSL。

  • server_name: This defines your server name and the server block that should be used for requests to your server. Be sure to replace example.com in this line with your own domain name.

    server_name :这定义您的服务器名称和用于请求服务器的服务器块。 请务必用您自己的域名替换这一行中的example.com

  • index: The index directive defines the files that will be used as indexes when processing requests to your server. We’ve modified the default order of priority here, moving index.php in front of index.html so that Nginx prioritizes files called index.php when possible.

    indexindex指令定义在处理对服务器的请求时将用作索引的文件。 我们在这里修改了默认的优先级顺序,将index.php移到了index.html前面,以便Nginx在可能的情况下优先处理名为index.php文件。

  • root: Our root directive names the root directory for requests to our server. This directory, /var/www/html, is created as a mount point at build time by instructions in our WordPress Dockerfile. These Dockerfile instructions also ensure that the files from the WordPress release are mounted to this volume.

    root :我们的root指令将根目录命名为服务器的请求目录。 根据WordPress Dockerfile中的指示,在构建时 /var/www/html这个目录创建为安装点 。 这些Dockerfile指令还确保将WordPress版本中的文件安装到该卷。

Location Blocks:

定位块:

  • location ~ /.well-known/acme-challenge: This location block will handle requests to the .well-known directory, where Certbot will place a temporary file to validate that the DNS for our domain resolves to our server. With this configuration in place, we will be able to use Certbot’s webroot plugin to obtain certificates for our domain.

    location ~ /.well-known/acme-challenge .well-known acme .well-known location ~ /.well-known/acme-challenge :此位置块将处理对.well-known目录的请求,Certbot将在其中放置一个临时文件,以验证我们域的DNS可以解析到我们的服务器。 有了此配置后,我们将能够使用Certbot的webroot插件来获取我们域的证书。

  • location /: In this location block, we’ll use a try_files directive to check for files that match individual URI requests. Instead of returning a 404 Not Found status as a default, however, we’ll pass control to WordPress’s index.php file with the request arguments.

    location / :在此location块中,我们将使用try_files指令来检查与单个URI请求匹配的文件。 但是,我们不会使用默认参数返回404 Not Found状态,而是将控制权传递给WordPress的index.php文件。

  • location ~ \.php$: This location block will handle PHP processing and proxy these requests to our wordpress container. Because our WordPress Docker image will be based on the php:fpm image, we will also include configuration options that are specific to the FastCGI protocol in this block. Nginx requires an independent PHP processor for PHP requests: in our case, these requests will be handled by the php-fpm processor that’s included with the php:fpm image. Additionally, this location block includes FastCGI-specific directives, variables, and options that will proxy requests to the WordPress application running in our wordpress container, set the preferred index for the parsed request URI, and parse URI requests.

    location ~ \.php$ :此location块将处理PHP处理并将这些请求代理到我们的wordpress容器。 因为我们的WordPress Docker映像将基于php:fpm映像 ,所以我们还将在此块中包含特定于FastCGI协议的配置选项。 Nginx需要一个独立PHP处理器来处理PHP请求:在我们的示例中,这些请求将由php:fpm映像随附的php-fpm处理器处理。 此外,此位置块包括特定于FastCGI的指令,变量和选项,这些指令会将请求代理到运行在wordpress容器中的WordPress应用程序,为解析的请求URI设置首选索引,并解析URI请求。

  • location ~ /\.ht: This block will handle .htaccess files since Nginx won’t serve them. The deny_all directive ensures that .htaccess files will never be served to users.

    location ~ /\.ht :由于Nginx不会为它们提供服务,因此该块将处理.htaccess文件。 deny_all指令可确保.htaccess文件永远不会提供给用户。

  • location = /favicon.ico, location = /robots.txt: These blocks ensure that requests to /favicon.ico and /robots.txt will not be logged.

    location = /favicon.ico location = /robots.txt :这些块可确保不会记录对/favicon.ico/robots.txt请求。

  • location ~* \.(css|gif|ico|jpeg|jpg|js|png)$: This block turns off logging for static asset requests and ensures that these assets are highly cacheable, as they are typically expensive to serve.

    location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ :此块关闭静态资产请求的日志记录,并确保这些资产具有很高的可缓存性,因为它们通常很昂贵。

For more information about FastCGI proxying, see Understanding and Implementing FastCGI Proxying in Nginx. For information about server and location blocks, see Understanding Nginx Server and Location Block Selection Algorithms.

有关FastCGI代理的更多信息,请参见了解和实现Nginx中的FastCGI代理 。 有关服务器和位置块的信息,请参阅了解Nginx服务器和位置块选择算法

Save and close the file when you are finished editing. If you used nano, do so by pressing CTRL+X, Y, then ENTER.

完成编辑后,保存并关闭文件。 如果您使用过nano ,请按CTRL+XY ,然后按ENTER

With your Nginx configuration in place, you can move on to creating environment variables to pass to your application and database containers at runtime.

完成Nginx配置后,您可以继续创建环境变量,以在运行时传递给应用程序和数据库容器。

第2步-定义环境变量 (Step 2 — Defining Environment Variables)

Your database and WordPress application containers will need access to certain environment variables at runtime in order for your application data to persist and be accessible to your application. These variables include both sensitive and non-sensitive information: sensitive values for your MySQL root password and application database user and password, and non-sensitive information for your application database name and host.

您的数据库和WordPress应用程序容器将需要在运行时访问某些环境变量,以使您的应用程序数据持久存在并可供您的应用程序访问。 这些变量包括敏感信息和非敏感信息:MySQL 密码和应用程​​序数据库用户和密码的敏感值,以及应用程序数据库名称和主机的非敏感信息。

Rather than setting all of these values in our Docker Compose file — the main file that contains information about how our containers will run — we can set the sensitive values in an .env file and restrict its circulation. This will prevent these values from copying over to our project repositories and being exposed publicly.

可以在.env文件中设置敏感值并限制其流通,而不是在Docker Compose文件(包含有关容器如何运行的信息的主文件)中设置所有这些值。 这将防止这些值复制到我们的项目存储库中并公开显示。

In your main project directory, ~/wordpress, open a file called .env:

在主项目目录~/ wordpress ,打开一个名为.env的文件:

  • nano .env

    纳米.env

The confidential 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 用户的密码以及WordPress将用于访问数据库的用户名和密码。

Add the following variable names and values to the file. Remember to supply your own values here for each variable:

将以下变量名称和值添加到文件中。 请记住在这里为每个变量提供自己的值

~/wordpress/.env
〜/ wordpress / .env
MYSQL_ROOT_PASSWORD=your_root_password
MYSQL_USER=your_wordpress_database_user
MYSQL_PASSWORD=your_wordpress_database_password

We have included a password for the root administrative account, as well as our preferred username and password for our application database.

我们已经包括了管理帐户的密码,以及我们的应用程序数据库的首选用户名和密码。

Save and close the file when you are finished editing.

完成编辑后,保存并关闭文件。

Because your .env file contains sensitive information, you will want to ensure that it is included in your project’s .gitignore and .dockerignore files, which tell Git and Docker what files not to copy to your Git repositories and Docker images, respectively.

因为您的.env文件包含敏感信息,所以您将要确保该文件包含在项目的.gitignore.dockerignore文件中,它们分别告诉Git和Docker哪些文件应该复制到Git存储库和Docker映像中。

If you plan to work with Git for version control, initialize your current working directory as a repository with git init:

如果您打算使用Git进行版本控制, 使用git init 将当前的工作目录初始化为存储库

  • git init

    git init

Then open a .gitignore file:

然后打开一个.gitignore文件:

  • nano .gitignore

    纳米.gitignore

Add .env to the file:

.env添加到文件中:

~/wordpress/.gitignore
〜/ wordpress / .gitignore
.env

Save and close the file when you are finished editing.

完成编辑后,保存并关闭文件。

Likewise, it’s a good precaution to add .env to a .dockerignore file, so that it doesn’t end up on your containers when you are using this directory as your build context.

同样,将.env添加到.dockerignore文件是一个很好的预防措施,因此当您将此目录用作构建上下文时,它不会最终出现在您的容器中。

Open the file:

打开文件:

  • nano .dockerignore

    纳米.dockerignore

Add .env to the file:

.env添加到文件中:

~/wordpress/.dockerignore
〜/ wordpress / .dockerignore
.env

Below this, you can optionally add files and directories associated with your application’s development:

在此之下,您可以选择添加与应用程序开发相关的文件和目录:

~/wordpress/.dockerignore
〜/ wordpress / .dockerignore
.env
.git
docker-compose.yml
.dockerignore

Save and close the file when you are finished.

完成后保存并关闭文件。

With your sensitive information in place, you can now move on to defining your services in a docker-compose.yml file.

设置好敏感信息后,您现在可以继续在docker-compose.yml文件中定义服务。

第3步—使用Docker Compose定义服务 (Step 3 — Defining Services with Docker Compose)

Your docker-compose.yml file will contain the service definitions for your setup. A service in Compose is a running container, and service definitions specify information about how each container will run.

docker-compose.yml文件将包含您设置的服务定义。 Compose中的服务是一个正在运行的容器,服务定义指定有关每个容器将如何运行的信息。

Using Compose, you can define different services in order to run multi-container applications, since Compose allows you to link these services together with shared networks and volumes. This will be helpful for our current setup since we will create different containers for our database, WordPress application, and web server. We will also create a container to run the Certbot client in order to obtain certificates for our webserver.

使用Compose,您可以定义不同的服务以运行多容器应用程序,因为Compose允许您将这些服务与共享网络和卷链接在一起。 这将对我们当前的设置有所帮助,因为我们将为数据库,WordPress应用程序和Web服务器创建不同的容器。 我们还将创建一个容器来运行Certbot客户端 ,以便为我们的Web服务器获取证书。

To begin, open the docker-compose.yml file:

首先,打开docker-compose.yml文件:

  • nano docker-compose.yml

    纳米docker-compose.yml

Add the following code to define your Compose file version and db database service:

添加以下代码以定义您的Compose文件版本和db数据库服务:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
version: '3'

services:
  db:
    image: mysql:8.0
    container_name: db
    restart: unless-stopped
    env_file: .env
    environment:
      - MYSQL_DATABASE=wordpress
    volumes: 
      - dbdata:/var/lib/mysql
    command: '--default-authentication-plugin=mysql_native_password'
    networks:
      - app-network

The db service definition contains the following options:

db服务定义包含以下选项:

  • image: This tells Compose what image to pull to create the container. We are pinning the mysql:8.0 image here to avoid future conflicts as the mysql:latest image continues to be updated. For more information about version pinning and avoiding dependency conflicts, see the Docker documentation on Dockerfile best practices.

    image :这告诉Compose要拉出什么图像来创建容器。 我们将mysql: 8.0映像固定在这里,以避免以后发生冲突,因为mysql:latest映像将继续更新。 有关版本固定和避免依赖性冲突的更多信息,请参阅Dockerfile最佳实践上的Docker文档。

  • container_name: This specifies a name for the container.

    container_name :这指定container_name的名称。

  • restart: This defines the container restart policy. The default is no, but we have set the container to restart unless it is stopped manually.

    restart :这定义了容器重启策略。 默认值为no ,但是我们将容器设置为重新启动,除非手动将其停止。

  • env_file: This option tells Compose that we would like to add environment variables from a file called .env, located in our build context. In this case, the build context is our current directory.

    env_file :此选项告诉Compose我们想从位于构建上下文中的名为.env的文件中添加环境变量。 在这种情况下,构建上下文是我们的当前目录。

  • environment: This option allows you to add additional environment variables, beyond those defined in your .env file. We will set the MYSQL_DATABASE variable equal to wordpress to provide a name for our application database. Because this is non-sensitive information, we can include it directly in the docker-compose.yml file.

    environment :此选项允许您添加其他环境变量,而.env.env文件中定义的变量。 我们将设置MYSQL_DATABASE变量等于wordpress ,以为我们的应用程序数据库提供一个名称。 由于这是非敏感信息,因此我们可以将其直接包含在docker-compose.yml文件中。

  • volumes: Here, we’re mounting a named volume called dbdata to the /var/lib/mysql directory on the container. This is the standard data directory for MySQL on most distributions.

    volumes :在这里,我们安装了一个名为容积称为dbdata/var/lib/mysql容器上的目录。 这是大多数发行版上MySQL的标准数据目录。

  • command: This option specifies a command to override the default CMD instruction for the image. In our case, we will add an option to the Docker image’s standard mysqld command, which starts the MySQL server on the container. This option, --default-authentication-plugin=mysql_native_password, sets the --default-authentication-plugin system variable to mysql_native_password, specifying which authentication mechanism should govern new authentication requests to the server. Since PHP and therefore our WordPress image won’t support MySQL’s newer authentication default, we must make this adjustment in order to authenticate our application database user.

    command :此选项指定一个命令来覆盖图像的默认CMD指令 。 在我们的例子中,我们将为Docker映像的标准mysqld命令添加一个选项,该选项将在容器上启动MySQL服务器。 --default-authentication-plugin=mysql_native_password这个选项将--default-authentication-plugin系统变量设置为mysql_native_password ,指定哪种身份验证机制应管理对服务器的新身份验证请求。 由于PHP以及我们的WordPress映像将不支持 MySQL的较新的默认身份验证 ,因此我们必须进行此调整才能对我们的应用程序数据库用户进行身份验证。

  • networks: This specifies that our application service will join the app-network network, which we will define at the bottom of the file.

    networks :这指定我们的应用程序服务将加入app-network网络,该网络将在文件底部定义。

Next, below your db service definition, add the definition for your wordpress application service:

接下来,在您的db服务定义下面,为您的wordpress应用程序服务添加定义:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
...
  wordpress:
    depends_on: 
      - db
    image: wordpress:5.1.1-fpm-alpine
    container_name: wordpress
    restart: unless-stopped
    env_file: .env
    environment:
      - WORDPRESS_DB_HOST=db:3306
      - WORDPRESS_DB_USER=$MYSQL_USER
      - WORDPRESS_DB_PASSWORD=$MYSQL_PASSWORD
      - WORDPRESS_DB_NAME=wordpress
    volumes:
      - wordpress:/var/www/html
    networks:
      - app-network

In this service definition, we are naming our container and defining a restart policy, as we did with the db service. We’re also adding some options specific to this container:

在此服务定义中,我们将为容器命名并定义一个重新启动策略,就像对db服务所做的那样。 我们还添加了一些特定于此容器的选项:

  • depends_on: This option ensures that our containers will start in order of dependency, with the wordpress container starting after the db container. Our WordPress application relies on the existence of our application database and user, so expressing this order of dependency will enable our application to start properly.

    depends_on :此选项可确保我们的容器将按依赖性顺序启动,而wordpress容器将在db容器之后启动。 我们的WordPress应用程序依赖于我们的应用程序数据库和用户的存在,因此表达这种依赖性顺序将使我们的应用程序能够正常启动。

  • image: For this setup, we are using the 5.1.1-fpm-alpine WordPress image. As discussed in Step 1, using this image ensures that our application will have the php-fpm processor that Nginx requires to handle PHP processing. This is also an alpine image, derived from the Alpine Linux project, which will help keep our overall image size down. For more information about the benefits and drawbacks of using alpine images and whether or not this makes sense for your application, see the full discussion under the Image Variants section of the Docker Hub WordPress image page.

    image :对于此设置,我们使用5.1.1 -fpm-alpine WordPress图像 。 如步骤1所述 ,使用此映像可确保我们的应用程序具有Nginx处理PHP处理所需的php-fpm处理器。 这也是从Alpine Linux项目衍生而来的alpine图像,这将有助于减小整体图像尺寸。 有关使用alpine图像的alpine以及是否对您的应用程序有意义的更多信息,请参阅Docker Hub WordPress图像页面Image Variants部分下的完整讨论。

  • env_file: Again, we specify that we want to pull values from our .env file, since this is where we defined our application database user and password.

    env_file :再次,我们指定我们要从.env文件中提取值,因为这是我们定义应用程序数据库用户和密码的地方。

  • environment: Here, we’re using the values we defined in our .env file, but we’re assigning them to the variable names that the WordPress image expects: WORDPRESS_DB_USER and WORDPRESS_DB_PASSWORD. We’re also defining a WORDPRESS_DB_HOST, which will be the MySQL server running on the db container that’s accessible on MySQL’s default port, 3306. Our WORDPRESS_DB_NAME will be the same value we specified in the MySQL service definition for our MYSQL_DATABASE: wordpress.

    environment :在这里,我们使用在.env文件中定义的值,但我们将它们分配给WordPress图像期望的变量名称: WORDPRESS_DB_USERWORDPRESS_DB_PASSWORD 。 我们还定义了WORDPRESS_DB_HOST ,它将是在db容器上运行MySQL服务器,该db容器可通过MySQL的默认端口3306 。 我们的WORDPRESS_DB_NAME将与我们在MySQL服务定义中为MYSQL_DATABASE指定的值相同: wordpress

  • volumes: We are mounting a named volume called wordpress to the /var/www/html mountpoint created by the WordPress image. Using a named volume in this way will allow us to share our application code with other containers.

    volumes :我们正在将名为wordpress的命名卷安装到WordPress映像创建/var/www/html挂载点。 以这种方式使用命名卷将使我们能够与其他容器共享应用程序代码。

  • networks: We’re also adding the wordpress container to the app-network network.

    networks :我们还将wordpress容器添加到app-network网络。

Next, below the wordpress application service definition, add the following definition for your webserver Nginx service:

接下来,在wordpress应用程序服务定义下方,为您的webserver Nginx服务添加以下定义:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
...
  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
      - certbot-etc:/etc/letsencrypt
    networks:
      - app-network

Again, we’re naming our container and making it dependent on the wordpress container in order of starting. We’re also using an alpine image — the 1.15.12-alpine Nginx image.

同样,我们要命名容器,并使其按照启动顺序依赖于wordpress容器。 我们还使用了一个alpine图像1.15.12 -alpine Nginx图像

This service definition also includes the following options:

此服务定义还包括以下选项:

  • ports: This exposes port 80 to enable the configuration options we defined in our nginx.conf file in

    ports :这暴露了端口80以启用我们在nginx.conf文件中定义的配置选项

    • wordpress:/var/www/html: This will mount our WordPress application code to the /var/www/html directory, the directory we set as the root in our Nginx server block.

      wordpress:/var/www/html :这会将我们的WordPress应用程序代码安装到/var/www/html目录,该目录是我们在Nginx服务器块中设置的root

    • ./nginx-conf:/etc/nginx/conf.d: This will bind mount the Nginx configuration directory on the host to the relevant directory on the container, ensuring that any changes we make to files on the host will be reflected in the container.

      ./nginx-conf:/etc/nginx/conf.d :这会将主机上的Nginx配置目录的安装绑定到容器上的相关目录,以确保我们对主机上的文件所做的任何更改都将反映在容器。

    • certbot-etc:/etc/letsencrypt: This will mount the relevant Let’s Encrypt certificates and keys for our domain to the appropriate directory on the container.

      certbot-etc:/etc/letsencrypt :这会将域的相关“让我们加密”证书和密钥安装到容器上的相应目录。

    volumes: Here, we are defining a combination of named volumes and bind mounts:

    volumes :在这里,我们定义了命名卷和绑定挂载的组合:

And again, we’ve added this container to the app-network network.

再次,我们已将此容器添加到app-network网络。

Finally, below your webserver definition, add your last service definition for the certbot service. Be sure to replace the email address and domain names listed here with your own information:

最后,在您的webserver定义下方,为certbot服务添加最后一个服务定义。 确保使用您自己的信息替换此处列出的电子邮件地址和域名:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
certbot:
    depends_on:
      - webserver
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - wordpress:/var/www/html
    command: certonly --webroot --webroot-path=/var/www/html --email sammy@example.com --agree-tos --no-eff-email --staging -d example.com -d www.example.com

This definition tells Compose to pull the certbot/certbot image from Docker Hub. It also uses named volumes to share resources with the Nginx container, including the domain certificates and key in certbot-etc and the application code in wordpress.

此定义告诉Compose从Docker Hub中提取certbot/certbot映像 。 它还使用命名卷与Nginx容器共享资源,包括certbot-etc的域证书和密钥以及wordpress的应用程序代码。

Again, we’ve used depends_on to specify that the certbot container should be started once the webserver service is running.

同样,我们使用了depends_on来指定一旦webserver服务运行,就应该启动certbot容器。

We’ve also included a command option that specifies a subcommand to run with the container’s default certbot command. The certonly subcommand will obtain a certificate with the following options:

我们还包括一个command选项,该选项指定一个子命令以与容器的默认certbot命令一起运行。 certonly子命令将获得具有以下选项的证书:

  • --webroot: This tells Certbot to use the webroot plugin to place files in the webroot folder for authentication. This plugin depends on the HTTP-01 validation method, which uses an HTTP request to prove that Certbot can access resources from a server that responds to a given domain name.

    --webroot :这告诉Certbot使用webroot插件将文件放在webroot文件夹中进行身份验证。 此插件取决于HTTP-01验证方法 ,该方法使用HTTP请求来证明Certbot可以从响应给定域名的服务器访问资源。

  • --webroot-path: This specifies the path of the webroot directory.

    --webroot-path :这指定了webroot目录的路径。

  • --email: Your preferred email for registration and recovery.

    --email :用于注册和恢复的首选电子邮件。

  • --agree-tos: This specifies that you agree to ACME’s Subscriber Agreement.

    --agree-tos :这表示您同意ACME的订购者协议

  • --no-eff-email: This tells Certbot that you do not wish to share your email with the Electronic Frontier Foundation (EFF). Feel free to omit this if you would prefer.

    --no-eff-email :这告诉Certbot您不希望与电子前沿基金会 (EFF)共享您的电子邮件。 如果愿意,可以忽略它。

  • --staging: This tells Certbot that you would like to use Let’s Encrypt’s staging environment to obtain test certificates. Using this option allows you to test your configuration options and avoid possible domain request limits. For more information about these limits, please see Let’s Encrypt’s rate limits documentation.

    --staging :这告诉Certbot您想使用Let's Encrypt的登台环境来获取测试证书。 使用此选项,您可以测试配置选项,并避免可能的域请求限制。 有关这些限制的更多信息,请参阅Let's Encrypt的速率限制文档

  • -d: This allows you to specify domain names you would like to apply to your request. In this case, we’ve included example.com and www.example.com. Be sure to replace these with your own domain.

    -d :这允许您指定要应用于您的请求的域名。 在这种情况下,我们包含了example.comwww. example.com www. example.com 。 确保将它们替换为您自己的域。

Below the certbot service definition, add your network and volume definitions:

certbot服务定义下,添加您的网络和卷定义:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
...
volumes:
  certbot-etc:
  wordpress:
  dbdata:

networks:
  app-network:
    driver: bridge

Our top-level volumes key defines the volumes certbot-etc, wordpress, and dbdata. When Docker creates volumes, the contents of the volume are stored in a directory on the host filesystem, /var/lib/docker/volumes/, that’s managed by Docker. The contents of each volume then get mounted from this directory to any container that uses the volume. In this way, it’s possible to share code and data between containers.

我们的顶级volumes密钥定义了certbot-etcwordpressdbdata 。 Docker创建卷时,卷的内容存储在主机文件系统/var/lib/docker/volumes/的目录中,该目录由Docker管理。 然后,每个卷的内容将从该目录挂载到使用该卷的任何容器中。 这样,可以在容器之间共享代码和数据。

The user-defined bridge network app-network enables communication between our containers since they are on the same Docker daemon host. This streamlines traffic and communication within the application, as it opens all ports between containers on the same bridge network without exposing any ports to the outside world. Thus, our db, wordpress, and webserver containers can communicate with each other, and we only need to expose port 80 for front-end access to the application.

用户定义的网桥网络app-network可在我们的容器之间进行通信,因为它们位于同一Docker守护程序主机上。 这可以简化应用程序内的通信和通讯,因为它可以打开同一网桥网络上容器之间的所有端口,而不会向外界暴露任何端口。 因此,我们的dbwordpresswebserver容器可以相互通信,我们只需要公开端口80前端访问该应用程序。

The finished docker-compose.yml file will look like this:

完成docker-compose.yml文件如下所示:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
version: '3'

services:
  db:
    image: mysql:8.0
    container_name: db
    restart: unless-stopped
    env_file: .env
    environment:
      - MYSQL_DATABASE=wordpress
    volumes: 
      - dbdata:/var/lib/mysql
    command: '--default-authentication-plugin=mysql_native_password'
    networks:
      - app-network

  wordpress:
    depends_on: 
      - db
    image: wordpress:5.1.1-fpm-alpine
    container_name: wordpress
    restart: unless-stopped
    env_file: .env
    environment:
      - WORDPRESS_DB_HOST=db:3306
      - WORDPRESS_DB_USER=$MYSQL_USER
      - WORDPRESS_DB_PASSWORD=$MYSQL_PASSWORD
      - WORDPRESS_DB_NAME=wordpress
    volumes:
      - wordpress:/var/www/html
    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
      - certbot-etc:/etc/letsencrypt
    networks:
      - app-network

  certbot:
    depends_on:
      - webserver
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - wordpress:/var/www/html
    command: certonly --webroot --webroot-path=/var/www/html --email sammy@example.com --agree-tos --no-eff-email --staging -d example.com -d www.example.com

volumes:
  certbot-etc:
  wordpress:
  dbdata:

networks:
  app-network:
    driver: bridge

Save and close the file when you are finished editing.

完成编辑后,保存并关闭文件。

With your service definitions in place, you are ready to start the containers and test your certificate requests.

有了服务定义之后,就可以启动容器并测试证书请求了。

第4步-获取SSL证书和凭证 (Step 4 — Obtaining SSL Certificates and Credentials)

We can start our containers with the docker-compose up command, which will create and run our containers in the order we have specified. If our domain requests are successful, we will see the correct exit status in our output and the right certificates mounted in the /etc/letsencrypt/live folder on the webserver container.

我们可以使用docker-compose up命令启动容器,该命令将按照指定的顺序创建和运行容器。 如果我们的域请求成功,我们将在输出中看到正确的退出状态,并在webserver容器的/etc/letsencrypt/live文件夹中安装正确的证书。

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

使用docker-compose up-d标志创建容器,这将在后台运行dbwordpresswebserver容器:

  • docker-compose up -d

    docker-compose up -d

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

您将看到输出确认您的服务已创建:


   
   
Output
Creating db ... done Creating wordpress ... done Creating webserver ... done Creating certbot ... done

Using docker-compose ps, check the status of your services:

使用docker-compose ps ,检查服务状态:

  • docker-compose ps

    码头工人组成ps

If everything was successful, your db, wordpress, and webserver services will be Up and the certbot container will have exited with a 0 status message:

如果一切成功,则您的dbwordpresswebserver服务将Up ,并且certbot容器将退出,并且状态消息为0


   
   
Output
Name Command State Ports ------------------------------------------------------------------------- certbot certbot certonly --webroot ... Exit 0 db docker-entrypoint.sh --def ... Up 3306/tcp, 33060/tcp webserver nginx -g daemon off; Up 0.0.0.0:80->80/tcp wordpress docker-entrypoint.sh php-fpm Up 9000/tcp

If you see anything other than Up in the State column for the db, wordpress, or webserver services, or an exit status other than 0 for the certbot container, be sure to check the service logs with the docker-compose logs command:

如果您在dbwordpresswebserver服务的State列中看到Up以外的任何内容,或者certbot容器的退出状态不是0的退出状态,请确保使用certbot docker-compose logs命令检查服务日志:

  • docker-compose logs service_name

    docker-compose日志service_name

You can now check that your certificates have been mounted to the webserver container with docker-compose exec:

现在,您可以使用docker-compose exec检查证书是否已安装到webserver容器:

  • docker-compose exec webserver ls -la /etc/letsencrypt/live

    docker-compose exec webserver ls -la / etc / letsencrypt / live

If your certificate requests were successful, you will see output like this:

如果您的证书请求成功,您将看到以下输出:


   
   
Output
total 16 drwx------ 3 root root 4096 May 10 15:45 . drwxr-xr-x 9 root root 4096 May 10 15:45 .. -rw-r--r-- 1 root root 740 May 10 15:45 README drwxr-xr-x 2 root root 4096 May 10 15:45 example.com

Now that you know your request will be successful, you can edit the certbot service definition to remove the --staging flag.

现在您知道您的请求将会成功,您可以编辑certbot服务定义以删除--staging标志。

Open docker-compose.yml:

打开docker-compose.yml

  • nano docker-compose.yml

    纳米docker-compose.yml

Find the section of the file with the certbot service definition, and replace the --staging flag in the command option with the --force-renewal flag, which will tell Certbot that you want to request a new certificate with the same domains as an existing certificate. The certbot service definition will now look like this:

找到带有certbot服务定义的文件部分,然后将command选项中的--staging标志替换为--force-renewal标志,这将告诉Certbot您要请求一个与域相同的新证书。现有证书。 certbot服务定义现在将如下所示:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
...
  certbot:
    depends_on:
      - webserver
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - certbot-var:/var/lib/letsencrypt
      - wordpress:/var/www/html
    command: certonly --webroot --webroot-path=/var/www/html --email sammy@example.com --agree-tos --no-eff-email --force-renewal -d example.com -d www.example.com
...

You can now run docker-compose up to recreate the certbot container. We will also include the --no-deps option to tell Compose that it can skip starting the webserver service, since it is already running:

现在,您可以运行certbot docker-compose up来重新创建certbot容器。 我们还将包括--no-deps选项,以告知Compose可以跳过启动webserver服务的步骤,因为该服务已经在运行:

  • docker-compose up --force-recreate --no-deps certbot

    docker-compose up --force-recreate --no-deps certbot

You will see output indicating that your certificate request was successful:

您将看到表明您的证书申请成功的输出:


   
   
Output
Recreating certbot ... done Attaching to certbot certbot | Saving debug log to /var/log/letsencrypt/letsencrypt.log certbot | Plugins selected: Authenticator webroot, Installer None certbot | Renewing an existing certificate certbot | Performing the following challenges: certbot | http-01 challenge for example.com certbot | http-01 challenge for www.example.com certbot | Using the webroot path /var/www/html for all unmatched domains. certbot | Waiting for verification... certbot | Cleaning up challenges certbot | IMPORTANT NOTES: certbot | - Congratulations! Your certificate and chain have been saved at: certbot | /etc/letsencrypt/live/example.com/fullchain.pem certbot | Your key file has been saved at: certbot | /etc/letsencrypt/live/example.com/privkey.pem certbot | Your cert will expire on 2019-08-08. To obtain a new or tweaked certbot | version of this certificate in the future, simply run certbot certbot | again. To non-interactively renew *all* of your certificates, run certbot | "certbot renew" certbot | - Your account credentials have been saved in your Certbot certbot | configuration directory at /etc/letsencrypt. You should make a certbot | secure backup of this folder now. This configuration directory will certbot | also contain certificates and private keys obtained by Certbot so certbot | making regular backups of this folder is ideal. certbot | - If you like Certbot, please consider supporting our work by: certbot | certbot | Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate certbot | Donating to EFF: https://eff.org/donate-le certbot | certbot exited with code 0

With your certificates in place, you can move on to modifying your Nginx configuration to include SSL.

放置好证书后,您可以继续修改Nginx配置以包括SSL。

步骤5 —修改Web服务器配置和服务定义 (Step 5 — Modifying the Web Server Configuration and Service Definition)

Enabling SSL in our Nginx configuration will involve adding an HTTP redirect to HTTPS, specifying our SSL certificate and key locations, and adding security parameters and headers.

在我们的Nginx配置中启用SSL将涉及向HTTPS添加HTTP重定向,指定我们的SSL证书和密钥位置以及添加安全性参数和标头。

Since you are going to recreate the webserver service to include these additions, you can stop it now:

由于您将重新创建webserver服务以包括这些附加功能,因此现在可以停止它:

  • docker-compose stop webserver

    docker-compose停止网络服务器

Before we modify the configuration file itself, let’s first get the recommended Nginx security parameters from Certbot using curl:

在修改配置文件本身之前,让我们首先使用curl从Certbot获取推荐的Nginx安全参数

  • curl -sSLo nginx-conf/options-ssl-nginx.conf https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf

    curl -sSLo nginx-conf / options-ssl-nginx.conf https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf

This command will save these parameters in a file called options-ssl-nginx.conf, located in the nginx-conf directory.

此命令会将这些参数保存在nginx-conf目录中的名为options-ssl-nginx.conf文件中。

Next, remove the Nginx configuration file you created earlier:

接下来,删除您先前创建的Nginx配置文件:

  • rm nginx-conf/nginx.conf

    rm nginx-conf / nginx.conf

Open another version of the file:

打开文件的另一个版本:

  • nano nginx-conf/nginx.conf

    纳米nginx-conf / nginx.conf

Add the following code to the file to redirect HTTP to HTTPS and to add SSL credentials, protocols, and security headers. Remember to replace example.com with your own domain:

将以下代码添加到文件中,以将HTTP重定向到HTTPS并添加SSL凭据,协议和安全标头。 请记住用您自己的域替换example.com

~/wordpress/nginx-conf/nginx.conf
〜/ wordpress / nginx-conf / nginx.conf
server {
        listen 80;
        listen [::]:80;

        server_name example.com www.example.com;

        location ~ /.well-known/acme-challenge {
                allow all;
                root /var/www/html;
        }

        location / {
                rewrite ^ https://$host$request_uri? permanent;
        }
}

server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name example.com www.example.com;

        index index.php index.html index.htm;

        root /var/www/html;

        server_tokens off;

        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        include /etc/nginx/conf.d/options-ssl-nginx.conf;

        add_header X-Frame-Options "SAMEORIGIN" always;
        add_header X-XSS-Protection "1; mode=block" always;
        add_header X-Content-Type-Options "nosniff" always;
        add_header Referrer-Policy "no-referrer-when-downgrade" always;
        add_header Content-Security-Policy "default-src * data: 'unsafe-eval' 'unsafe-inline'" always;
        # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
        # enable strict transport security only if you understand the implications

        location / {
                try_files $uri $uri/ /index.php$is_args$args;
        }

        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass wordpress:9000;
                fastcgi_index index.php;
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_path_info;
        }

        location ~ /\.ht {
                deny all;
        }

        location = /favicon.ico { 
                log_not_found off; access_log off; 
        }
        location = /robots.txt { 
                log_not_found off; access_log off; allow all; 
        }
        location ~* \.(css|gif|ico|jpeg|jpg|js|png)$ {
                expires max;
                log_not_found off;
        }
}

The HTTP server block specifies the webroot for Certbot renewal requests to the .well-known/acme-challenge directory. It also includes a rewrite directive that directs HTTP requests to the root directory to HTTPS.

HTTP服务器块将Certbot续订请求的Webroot指定到.well .well-known/acme-challenge目录。 它还包括一个重写指令 ,该指令将HTTP请求发送到HTTPS的根目录。

The HTTPS server block enables ssl and http2. To read more about how HTTP/2 iterates on HTTP protocols and the benefits it can have for website performance, please see the introduction to How To Set Up Nginx with HTTP/2 Support on Ubuntu 18.04.

HTTPS服务器块启用sslhttp2 。 要了解有关HTTP / 2如何在HTTP协议上进行迭代以及其对网站性能的好处的更多信息,请参阅“ 如何在Ubuntu 18.04上设置具有HTTP / 2支持的Nginx”的介绍。

This block also includes our SSL certificate and key locations, along with the recommended Certbot security parameters that we saved to nginx-conf/options-ssl-nginx.conf.

该块还包括我们的SSL证书和密钥位置,以及我们保存到nginx-conf/options-ssl-nginx.conf的建议的Certbot安全参数。

Additionally, we’ve included some security headers that will enable us to get A ratings on things like the SSL Labs and Security Headers server test sites. These headers include X-Frame-Options, X-Content-Type-Options, Referrer Policy, Content-Security-Policy, and X-XSS-Protection. The HTTP Strict Transport Security (HSTS) header is commented out — enable this only if you understand the implications and have assessed its “preload” functionality.

此外,我们包含了一些安全标头,使我们能够在SSL实验室安全标头服务器测试站点等方面获得A评级。 这些标头包括X-Frame-OptionsX-Content-Type-OptionsReferrer PolicyContent-Security-PolicyX-XSS-ProtectionHTTP Strict Transport Security (HSTS)标头已被注释掉-仅在您了解其含义并评估了其“预加载”功能后,才能启用此标头。

Our root and index directives are also located in this block, as are the rest of the WordPress-specific location blocks discussed in Step 1.

我们的rootindex指令也位于此块中, 步骤1中讨论的其余WordPress特定位置块也是如此。

Once you have finished editing, save and close the file.

完成编辑后,保存并关闭文件。

Before recreating the webserver service, you will need to add a 443 port mapping to your webserver service definition.

在重新创建webserver服务之前,需要将443端口映射添加到webserver服务定义。

Open your docker-compose.yml file:

打开您docker-compose.yml文件:

  • nano docker-compose.yml

    纳米docker-compose.yml

In the webserver service definition, add the following port mapping:

webserver服务定义中,添加以下端口映射:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
...
  webserver:
    depends_on:
      - wordpress
    image: nginx:1.15.12-alpine
    container_name: webserver
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - wordpress:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
      - certbot-etc:/etc/letsencrypt
    networks:
      - app-network

The docker-compose.yml file will look like this when finished:

完成后, docker-compose.yml文件将如下所示:

~/wordpress/docker-compose.yml
〜/ wordpress / docker-compose.yml
version: '3'

services:
  db:
    image: mysql:8.0
    container_name: db
    restart: unless-stopped
    env_file: .env
    environment:
      - MYSQL_DATABASE=wordpress
    volumes: 
      - dbdata:/var/lib/mysql
    command: '--default-authentication-plugin=mysql_native_password'
    networks:
      - app-network

  wordpress:
    depends_on: 
      - db
    image: wordpress:5.1.1-fpm-alpine
    container_name: wordpress
    restart: unless-stopped
    env_file: .env
    environment:
      - WORDPRESS_DB_HOST=db:3306
      - WORDPRESS_DB_USER=$MYSQL_USER
      - WORDPRESS_DB_PASSWORD=$MYSQL_PASSWORD
      - WORDPRESS_DB_NAME=wordpress
    volumes:
      - wordpress:/var/www/html
    networks:
      - app-network

  webserver:
    depends_on:
      - wordpress
    image: nginx:1.15.12-alpine
    container_name: webserver
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - wordpress:/var/www/html
      - ./nginx-conf:/etc/nginx/conf.d
      - certbot-etc:/etc/letsencrypt
    networks:
      - app-network

  certbot:
    depends_on:
      - webserver
    image: certbot/certbot
    container_name: certbot
    volumes:
      - certbot-etc:/etc/letsencrypt
      - wordpress:/var/www/html
    command: certonly --webroot --webroot-path=/var/www/html --email sammy@example.com --agree-tos --no-eff-email --force-renewal -d example.com -d www.example.com

volumes:
  certbot-etc:
  wordpress:
  dbdata:

networks:
  app-network:
    driver: bridge

Save and close the file when you are finished editing.

完成编辑后,保存并关闭文件。

Recreate the webserver service:

重新创建webserver服务:

  • docker-compose up -d --force-recreate --no-deps webserver

    docker-compose up -d --force-recreate --no-deps网络服务器

Check your services with docker-compose ps:

使用docker-compose ps检查您的服务:

  • docker-compose ps

    码头工人组成ps

You should see output indicating that your db, wordpress, and webserver services are running:

您应该看到输出指示您的dbwordpresswebserver服务正在运行:


   
   
Output
Name Command State Ports ---------------------------------------------------------------------------------------------- certbot certbot certonly --webroot ... Exit 0 db docker-entrypoint.sh --def ... Up 3306/tcp, 33060/tcp webserver nginx -g daemon off; Up 0.0.0.0:443->443/tcp, 0.0.0.0:80->80/tcp wordpress docker-entrypoint.sh php-fpm Up 9000/tcp

With your containers running, you can now complete your WordPress installation through the web interface.

随着容器的运行,您现在可以通过Web界面完成WordPress的安装。

步骤6 —通过Web界面完成安装 (Step 6 — Completing the Installation Through the Web Interface)

With our containers running, we can finish the installation through the WordPress web interface.

随着容器的运行,我们可以通过WordPress Web界面完成安装。

In your web browser, navigate to your server’s domain. Remember to substitute example.com here with your own domain name:

在您的Web浏览器中,导航到服务器的域。 请记住在此处用您自己的域名替换example.com

https://example.com

Select the language you would like to use:

选择您要使用的语言:

After clicking Continue, you will land on the main setup page, where you will need to pick a name for your site and a username. It’s a good idea to choose a memorable username here (rather than “admin”) and a strong password. You can use the password that WordPress generates automatically or create your own.

单击“ 继续”后 ,您将进入主设置页面,在该页面上,您将需要为网站选择一个名称和一个用户名。 在这里选择一个难忘的用户名(而不是“ admin”)和一个强密码是个好主意。 您可以使用WordPress自动生成的密码或创建自己的密码。

Finally, you will need to enter your email address and decide whether or not you want to discourage search engines from indexing your site:

最后,您将需要输入电子邮件地址并确定是否要阻止搜索引擎将您的网站编入索引:

Clicking on Install WordPress at the bottom of the page will take you to a login prompt:

单击页面底部的“ 安装WordPress ”将带您进入登录提示:

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

登录后,您将可以访问WordPress管理信息中心:

With your WordPress installation complete, you can now take steps to ensure that your SSL certificates will renew automatically.

完成WordPress的安装后,您现在可以采取步骤以确保SSL证书将自动更新。

第7步-更新证书 (Step 7 — Renewing Certificates)

Let’s Encrypt certificates are valid for 90 days, so you will want to set up an automated renewal process to ensure that they do not lapse. One way to do this is to create a job with the cron scheduling utility. In this case, we will create a cron job to periodically run a script that will renew our certificates and reload our Nginx configuration.

让我们加密证书有效期为90天,因此您将需要设置一个自动续订过程以确保它们不会失效。 一种方法是使用cron调度实用程序创建作业。 在这种情况下,我们将创建一个cron作业以定期运行脚本,该脚本将更新我们的证书并重新加载我们的Nginx配置。

First, open a script called ssl_renew.sh:

首先,打开一个名为ssl_renew.sh的脚本:

  • nano ssl_renew.sh

    纳米ssl_renew.sh

Add the following code to the script to renew your certificates and reload your web server configuration. Remember to replace the example username here with your own non-root username:

将以下代码添加到脚本中以续订证书并重新加载Web服务器配置。 请记住,将此处的示例用户名替换为您自己的非root用户名:

~/wordpress/ssl_renew.sh
〜/ wordpress / ssl_renew.sh
#!/bin/bash

COMPOSE="/usr/local/bin/docker-compose --no-ansi"
DOCKER="/usr/bin/docker"

cd /home/sammy/wordpress/
$COMPOSE run certbot renew --dry-run && $COMPOSE kill -s SIGHUP webserver
$DOCKER system prune -af

This script first assigns the docker-compose binary to a variable called COMPOSE, and specifies the --no-ansi option, which will run docker-compose commands without ANSI control characters. It then does the same with the docker binary. Finally, it changes to the ~/wordpress project directory and runs the following docker-compose commands:

该脚本首先将docker-compose二进制文件分配给名为COMPOSE的变量,并指定--no-ansi选项,该选项将运行不带ANSI控制字符的 docker-compose命令。 然后,它对docker二进制文件执行相同的操作。 最后,它切换到~/wordpress项目目录,并运行以下docker-compose命令:

  • docker-compose run: This will start a certbot container and override the command provided in our certbot service definition. Instead of using the certonly subcommand, we’re using the renew subcommand here, which will renew certificates that are close to expiring. We’ve included the --dry-run option here to test our script.

    certbot docker-compose run :这将启动certbot容器并覆盖我们certbot服务定义中提供的commandcertonly不使用certonly子命令,而是使用renew子命令,该命令将更新即将到期的证书。 我们在此处包括--dry-run选项,以测试脚本。

  • docker-compose kill: This will send a SIGHUP signal to the webserver container to reload the Nginx configuration. For more information on using this process to reload your Nginx configuration, please see this Docker blog post on deploying the official Nginx image with Docker.

    docker-compose kill :这会将SIGHUP信号发送到webserver容器以重新加载Nginx配置。 有关使用此过程重新加载Nginx配置的更多信息,请参阅此Docker博客文章,了解如何使用Docker部署官方Nginx映像

It then runs docker system prune to remove all unused containers and images.

然后运行docker system prune删除所有未使用的容器和映像。

Close the file when you are finished editing. Make it executable:

完成编辑后,关闭文件。 使它可执行:

  • chmod +x ssl_renew.sh

    chmod + x ssl_renew.sh

Next, open your root crontab file to run the renewal script at a specified interval:

接下来,打开您的crontab 文件,以指定的时间间隔运行续订脚本:

  • sudo crontab -e

    须藤crontab -e

If this is your first time editing this file, you will be asked to choose an editor:

如果这是您第一次编辑此文件,将要求您选择编辑器:


   
   
Output
no crontab for root - using an empty one Select an editor. To change later, run 'select-editor'. 1. /bin/nano <---- easiest 2. /usr/bin/vim.basic 3. /usr/bin/vim.tiny 4. /bin/ed Choose 1-4 [1]: ...

At the bottom of the file, add the following line:

在文件底部,添加以下行:

crontab
crontab
...
*/5 * * * * /home/sammy/wordpress/ssl_renew.sh >> /var/log/cron.log 2>&1

This will set the job interval to every five minutes, so you can test whether or not your renewal request has worked as intended. We have also created a log file, cron.log, to record relevant output from the job.

这会将作业间隔设置为每五分钟一次,因此您可以测试您的续订请求是否按预期进行。 我们还创建了一个日志文件cron.log ,以记录作业的相关输出。

After five minutes, check cron.log to see whether or not the renewal request has succeeded:

五分钟后,检查cron.log以查看续订请求是否成功:

  • tail -f /var/log/cron.log

    尾巴-f /var/log/cron.log

You should see output confirming a successful renewal:

您应该看到确认续订成功的输出:


   
   
Output
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ** DRY RUN: simulating 'certbot renew' close to cert expiry ** (The test certificates below have not been saved.) Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/example.com/fullchain.pem (success) ** DRY RUN: simulating 'certbot renew' close to cert expiry ** (The test certificates above have not been saved.) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

You can now modify the crontab file to set a daily interval. To run the script every day at noon, for example, you would modify the last line of the file to look like this:

现在,您可以修改crontab文件以设置每日间隔。 例如,要每天中午运行脚本,您可以将文件的最后一行修改为如下所示:

crontab
crontab
...
0 12 * * * /home/sammy/wordpress/ssl_renew.sh >> /var/log/cron.log 2>&1

You will also want to remove the --dry-run option from your ssl_renew.sh script:

您还将希望从ssl_renew.sh脚本中删除--dry-run选项:

~/wordpress/ssl_renew.sh
〜/ wordpress / ssl_renew.sh
#!/bin/bash

COMPOSE="/usr/local/bin/docker-compose --no-ansi"
DOCKER="/usr/bin/docker"

cd /home/sammy/wordpress/
$COMPOSE run certbot renew && $COMPOSE kill -s SIGHUP webserver
$DOCKER system prune -af

Your cron job will ensure that your Let’s Encrypt certificates don’t lapse by renewing them when they are eligible. You can also set up log rotation with the Logrotate utility to rotate and compress your log files.

您的cron作业将通过在符合条件的情况下进行续订来确保“让我们加密”证书不会失效。 您还可以使用Logrotate实用程序设置日志轮转,以旋转和压缩日志文件。

结论 (Conclusion)

In this tutorial, you used Docker Compose to create a WordPress installation with an Nginx web server. As part of this workflow, you obtained TLS/SSL certificates for the domain you want associated with your WordPress site. Additionally, you created a cron job to renew these certificates when necessary.

在本教程中,您使用Docker Compose通过Nginx Web服务器创建了WordPress安装。 作为此工作流程的一部分,您已获取要与WordPress网站关联的域的TLS / SSL证书。 此外,您创建了cron作业以在必要时续订这些证书。

As additional steps to improve site performance and redundancy, you can consult the following articles on delivering and backing up WordPress assets:

作为改善站点性能和冗余的其他步骤,您可以查阅以下有关交付和备份WordPress资产的文章:

If you are interested in exploring a containerized workflow with Kubernetes, you can also check out:

如果您对使用Kubernetes探索容器化工作流感兴趣,还可以签出以下内容:

翻译自: https://www.digitalocean.com/community/tutorials/how-to-install-wordpress-with-docker-compose

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值