The author selected The FreeBSD Foundation to receive a donation as part of the Write for DOnations program.
作者选择FreeBSD基金会作为Write for DOnations计划的一部分接受捐赠。
介绍 (Introduction)
Over the past few years, Docker has become a frequently used solution for deploying applications thanks to how it simplifies running and deploying applications in ephemeral containers. When using a LEMP application stack, for example, with PHP, Nginx, MySQL and the Laravel framework, Docker can significantly streamline the setup process.
在过去的几年中,由于Docker简化了在临时容器中运行和部署应用程序的方式,因此它已成为部署应用程序的常用解决方案。 例如,当使用LEMP应用程序堆栈以及PHP , Nginx , MySQL和Laravel框架时,Docker可以大大简化设置过程。
Docker Compose has further simplified the development process by allowing developers to define their infrastructure, including application services, networks, and volumes, in a single file. Docker Compose offers an efficient alternative to running multiple docker container create
and docker container run
commands.
Docker Compose通过允许开发人员在单个文件中定义其基础架构(包括应用程序服务,网络和卷),进一步简化了开发流程。 Docker Compose为运行多个docker container create
和docker container run
命令提供了一种有效的替代方法。
In this tutorial, you will build a web application using the Laravel framework, with Nginx as the web server and MySQL as the database, all inside Docker containers. You will define the entire stack configuration in a docker-compose
file, along with configuration files for PHP, MySQL, and Nginx.
在本教程中,您将使用Laravel框架构建一个Web应用程序,其中Nginx作为Web服务器,MySQL作为数据库,所有这些都在Docker容器内。 您将在docker-compose
文件中定义整个堆栈配置,以及PHP,MySQL和Nginx的配置文件。
先决条件 (Prerequisites)
Before you start, you will need:
在开始之前,您需要:
One Ubuntu 18.04 server, and a non-root user with
sudo
privileges. Follow the Initial Server Setup with Ubuntu 18.04 tutorial to set this up.一台Ubuntu 18.04服务器,以及一个具有
sudo
特权的非root用户。 请按照《 Ubuntu 18.04的初始服务器设置》教程进行设置。Docker installed, 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, following Step 1 of How To Install Docker Compose on Ubuntu 18.04.
第1步—下载Laravel和安装依赖项 (Step 1 — Downloading Laravel and Installing Dependencies)
As a first step, we will get the latest version of Laravel and install the dependencies for the project, including Composer, the application-level package manager for PHP. We will install these dependencies with Docker to avoid having to install Composer globally.
第一步,我们将获取最新版本的Laravel并安装项目的依赖项,包括Composer ,这是PHP的应用程序级包管理器。 我们将使用Docker安装这些依赖项,以避免必须全局安装Composer。
First, check that you are in your home directory and clone the latest Laravel release to a directory called laravel-app
:
首先,检查您是否位于主目录中,并将最新的Laravel版本克隆到名为laravel-app
的目录中:
- cd ~ 光盘〜
git clone https://github.com/laravel/laravel.git laravel-app
git clone https://github.com/laravel/laravel.git laravel-app
Move into the laravel-app
directory:
移至laravel-app
目录:
cd ~/laravel-app
cd〜 / laravel-app
Next, use Docker’s composer
image to mount the directories that you will need for your Laravel project and avoid the overhead of installing Composer globally:
接下来,使用Docker的composer
映像来安装Laravel项目所需的目录,并避免全局安装Composer的开销:
- docker run --rm -v $(pwd):/app composer install 泊坞窗运行--rm -v $ {pwd):/ app composer install
Using the -v
and --rm
flags with docker run
creates an ephemeral container that will be bind-mounted to your current directory before being removed. This will copy the contents of your ~/laravel-app
directory to the container and also ensure that the vendor
folder Composer creates inside the container is copied to your current directory.
使用-v
和--rm
标志与docker run
创造一个短暂的容器,这将是绑定挂载到当前目录被删除之前。 这会将~/ laravel-app
目录的内容复制到容器,并确保Composer在容器内部创建的vendor
文件夹被复制到当前目录。
As a final step, set permissions on the project directory so that it is owned by your non-root user:
最后一步,在项目目录上设置权限,以使其归您的非root用户所有:
- sudo chown -R $USER:$USER ~/laravel-app 须藤chown -R $ USER:$ USER〜/ laravel-app
This will be important when you write the Dockerfile for your application image in Step 4, as it will allow you to work with your application code and run processes in your container as a non-root user.
当您在步骤4中为应用程序映像编写Dockerfile时,这将很重要,因为它将允许您使用应用程序代码并以非root用户身份在容器中运行进程。
With your application code in place, you can move on to defining your services with Docker Compose.
放置好应用程序代码后,您可以继续使用Docker Compose定义服务。
第2步-创建Docker Compose文件 (Step 2 — Creating the Docker Compose File)
Building your applications with Docker Compose simplifies the process of setting up and versioning your infrastructure. To set up our Laravel application, we will write a docker-compose
file that defines our web server, database, and application services.
使用Docker Compose构建应用程序可简化基础架构的设置和版本控制过程。 要设置Laravel应用程序,我们将编写一个docker docker-compose
文件,该文件定义了我们的Web服务器,数据库和应用程序服务。
Open the file:
打开文件:
- nano ~/laravel-app/docker-compose.yml 纳米〜/ laravel-app / docker-compose.yml
In the docker-compose
file, you will define three services: app
, webserver
, and db
. Add the following code to the file, being sure to replace the root password for MYSQL_ROOT_PASSWORD
, defined as an environment variable under the db
service, with a strong password of your choice:
在docker-compose
文件中,您将定义三个服务: app
, webserver
和db
。 将以下代码添加到文件中,并确保使用您选择的强密码替换MYSQL_ROOT_PASSWORD
的根密码(在db
服务下定义为环境变量) :
version: '3'
services:
#PHP Service
app:
build:
context: .
dockerfile: Dockerfile
image: digitalocean.com/php
container_name: app
restart: unless-stopped
tty: true
environment:
SERVICE_NAME: app
SERVICE_TAGS: dev
working_dir: /var/www
networks:
- app-network
#Nginx Service
webserver:
image: nginx:alpine
container_name: webserver
restart: unless-stopped
tty: true
ports:
- "80:80"
- "443:443"
networks:
- app-network
#MySQL Service
db:
image: mysql:5.7.22
container_name: db
restart: unless-stopped
tty: true
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: laravel
MYSQL_ROOT_PASSWORD: your_mysql_root_password
SERVICE_TAGS: dev
SERVICE_NAME: mysql
networks:
- app-network
#Docker Networks
networks:
app-network:
driver: bridge
The services defined here include:
此处定义的服务包括:
app
: This service definition contains the Laravel application and runs a custom Docker image,digitalocean.com/php
, that you will define in Step 4. It also sets theworking_dir
in the container to/var/www
.app
:此服务定义包含Laravel应用程序,并运行一个自定义Docker映像digitalocean.com/php
,您将在步骤4中对其进行定义。它还将容器中的working_dir
设置为/var/www
。webserver
: This service definition pulls thenginx:alpine
image from Docker and exposes ports80
and443
.webserver
:此服务定义从Docker提取nginx:alpine
映像 ,并公开端口80
和443
。db
: This service definition pulls themysql:5.7.22
image from Docker and defines a few environmental variables, including a database calledlaravel
for your application and the root password for the database. You are free to name the database whatever you would like, and you should replaceyour_mysql_root_password
with your own strong password. This service definition also maps port3306
on the host to port3306
on the container.db
:此服务定义从Docker中提取mysql:5.7.22
映像 ,并定义了一些环境变量,包括用于您的应用程序的名为laravel
的数据库和该数据库的根密码。 您可以随意命名数据库,并且应使用自己的强密码替换your_mysql_root_password
。 该服务定义也映射端口3306
的主机端口3306
的容器上。
Each container_name
property defines a name for the container, which corresponds to the name of the service. If you don’t define this property, Docker will assign a name to each container by combining a historically famous person’s name and a random word separated by an underscore.
每个container_name
属性都为container_name
定义一个名称,该名称与服务名称相对应。 如果您未定义此属性,则Docker将通过结合历史上著名人物的名字和一个由下划线分隔的随机词来为每个容器分配一个名称。
To facilitate communication between containers, the services are connected to a bridge network called app-network
. A bridge network uses a software bridge that allows containers connected to the same bridge network to communicate with each other. The bridge driver automatically installs rules in the host machine so that containers on different bridge networks cannot communicate directly with each other. This creates a greater level of security for applications, ensuring that only related services can communicate with one another. It also means that you can define multiple networks and services connecting to related functions: front-end application services can use a frontend
network, for example, and back-end services can use a backend
network.
为了促进容器之间的通信,将服务连接到称为app-network
的桥app-network
。 桥网络使用软件桥,该软件桥允许连接到同一桥网络的容器相互通信。 桥驱动程序会自动在主机中安装规则,以使不同桥网络上的容器无法直接相互通信。 这为应用程序创建了更高级别的安全性,确保只有相关服务才能相互通信。 这也意味着您可以定义连接到相关功能的多个网络和服务:例如, frontend
应用程序服务可以使用frontend
网络,而后端服务可以使用backend
网络。
Let’s look at how to add volumes and bind mounts to your service definitions to persist your application data.
让我们看一下如何添加卷并将绑定绑定到服务定义以持久化应用程序数据。
步骤3 —保留数据 (Step 3 — Persisting Data)
Docker has powerful and convenient features for persisting data. In our application, we will make use of volumes and bind mounts for persisting the database, and application and configuration files. Volumes offer flexibility for backups and persistence beyond a container’s lifecycle, while bind mounts facilitate code changes during development, making changes to your host files or directories immediately available in your containers. Our setup will make use of both.
Docker具有强大而便捷的功能来持久化数据。 在我们的应用程序中,我们将使用卷和绑定挂载来持久化数据库,应用程序和配置文件。 卷提供了超出容器生命周期的备份和持久性的灵活性,而绑定挂载则有助于在开发过程中更改代码,从而可以对容器中的主机文件或目录进行立即更改。 我们的设置将同时使用两者。
Warning: By using bind mounts, you make it possible to change the host filesystem through processes running in a container, including creating, modifying, or deleting important system files or directories. This is a powerful ability with security implications, and could impact non-Docker processes on the host system. Use bind mounts with care.
警告:通过使用绑定装载,您可以通过容器中运行的进程来更改主机文件系统,包括创建,修改或删除重要的系统文件或目录。 这是一项具有安全隐患的强大功能,并且可能会影响主机系统上的非Docker进程。 小心使用装订架。
In the docker-compose
file, define a volume called dbdata
under the db
service definition to persist the MySQL database:
在dbdata
docker-compose
文件中,在db
服务定义下定义一个名为dbdata
的卷以保留MySQL数据库:
...
#MySQL Service
db:
...
volumes:
- dbdata:/var/lib/mysql
networks:
- app-network
...
The named volume dbdata
persists the contents of the /var/lib/mysql
folder present inside the container. This allows you to stop and restart the db
service without losing data.
命名卷dbdata
存在的/var/lib/mysql
文件夹的内容。 这使您可以停止并重新启动db
服务,而不会丢失数据。
At the bottom of the file, add the definition for the dbdata
volume:
在文件的底部,添加dbdata
卷的定义:
...
#Volumes
volumes:
dbdata:
driver: local
With this definition in place, you will be able to use this volume across services.
有了这个定义,您就可以跨服务使用此卷。
Next, add a bind mount to the db
service for the MySQL configuration files you will create in Step 7:
接下来,将绑定装载添加到将在步骤7中创建MySQL配置文件的db
服务中:
...
#MySQL Service
db:
...
volumes:
- dbdata:/var/lib/mysql
- ./mysql/my.cnf:/etc/mysql/my.cnf
...
This bind mount binds ~/laravel-app/mysql/my.cnf
to /etc/mysql/my.cnf
in the container.
这个绑定安装结合~/laravel-app/mysql/my.cnf
以/etc/mysql/my.cnf
在容器中。
Next, add bind mounts to the webserver
service. There will be two: one for your application code and another for the Nginx configuration definition that you will create in Step 6:
接下来,将绑定安装添加到webserver
服务。 将有两个:一个用于您的应用程序代码,另一个用于您将在步骤6中创建的Nginx配置定义:
#Nginx Service
webserver:
...
volumes:
- ./:/var/www
- ./nginx/conf.d/:/etc/nginx/conf.d/
networks:
- app-network
The first bind mount binds the application code in the ~/laravel-app
directory to the /var/www
directory inside the container. The configuration file that you will add to ~/laravel-app/nginx/conf.d/
will also be mounted to /etc/nginx/conf.d/
in the container, allowing you to add or modify the configuration directory’s contents as needed.
第一个绑定安装将~/laravel-app
目录中的应用程序代码绑定到容器内的/var/www
目录。 您将添加到~/laravel-app/nginx/conf.d/
的配置文件也将安装到/etc/nginx/conf.d/
中的/etc/nginx/conf.d/
中,从而允许您根据需要添加或修改配置目录的内容。
Finally, add the following bind mounts to the app
service for the application code and configuration files:
最后,将以下绑定装载添加到app
服务,以获取应用程序代码和配置文件:
#PHP Service
app:
...
volumes:
- ./:/var/www
- ./php/local.ini:/usr/local/etc/php/conf.d/local.ini
networks:
- app-network
The app
service is bind-mounting the ~/laravel-app
folder, which contains the application code, to the /var/www
folder in the container. This will speed up the development process, since any changes made to your local application directory will be instantly reflected inside the container. You are also binding your PHP configuration file, ~/laravel-app/php/local.ini
, to /usr/local/etc/php/conf.d/local.ini
inside the container. You will create the local PHP configuration file in Step 5.
app
服务将包含应用程序代码的~/laravel-app
文件夹绑定安装到容器中的/var/www
文件夹中。 这将加速开发过程,因为对本地应用程序目录所做的任何更改都会立即反映在容器内。 您还将PHP配置文件~/laravel-app/php/local.ini
绑定到容器内的/usr/local/etc/php/conf.d/local.ini
中。 您将在步骤5中创建本地PHP配置文件。
Your docker-compose
file will now look like this:
您的docker-compose
文件现在将如下所示:
version: '3'
services:
#PHP Service
app:
build:
context: .
dockerfile: Dockerfile
image: digitalocean.com/php
container_name: app
restart: unless-stopped
tty: true
environment:
SERVICE_NAME: app
SERVICE_TAGS: dev
working_dir: /var/www
volumes:
- ./:/var/www
- ./php/local.ini:/usr/local/etc/php/conf.d/local.ini
networks:
- app-network
#Nginx Service
webserver:
image: nginx:alpine
container_name: webserver
restart: unless-stopped
tty: true
ports:
- "80:80"
- "443:443"
volumes:
- ./:/var/www
- ./nginx/conf.d/:/etc/nginx/conf.d/
networks:
- app-network
#MySQL Service
db:
image: mysql:5.7.22
container_name: db
restart: unless-stopped
tty: true
ports:
- "3306:3306"
environment:
MYSQL_DATABASE: laravel
MYSQL_ROOT_PASSWORD: your_mysql_root_password
SERVICE_TAGS: dev
SERVICE_NAME: mysql
volumes:
- dbdata:/var/lib/mysql/
- ./mysql/my.cnf:/etc/mysql/my.cnf
networks:
- app-network
#Docker Networks
networks:
app-network:
driver: bridge
#Volumes
volumes:
dbdata:
driver: local
Save the file and exit your editor when you are finished making changes.
完成更改后,保存文件并退出编辑器。
With your docker-compose
file written, you can now build the custom image for your application.
编写好docker-compose
文件后,您现在可以为应用程序构建自定义映像。
第4步—创建Dockerfile (Step 4 — Creating the Dockerfile)
Docker allows you to specify the environment inside of individual containers with a Dockerfile. A Dockerfile enables you to create custom images that you can use to install the software required by your application and configure settings based on your requirements. You can push the custom images you create to Docker Hub or any private registry.
Docker允许您使用Dockerfile在单个容器内指定环境。 Dockerfile使您可以创建自定义映像,可用于安装应用程序所需的软件并根据需要配置设置。 您可以将创建的自定义映像推送到Docker Hub或任何私有注册表。
Our Dockerfile
will be located in our ~/laravel-app
directory. Create the file:
我们的Dockerfile
将位于我们的~/laravel-app
目录中。 创建文件:
- nano ~/laravel-app/Dockerfile 纳米〜/ laravel-app / Dockerfile
This Dockerfile
will set the base image and specify the necessary commands and instructions to build the Laravel application image. Add the following code to the file:
该Dockerfile
将设置基础映像并指定必要的命令和指令以构建Laravel应用程序映像。 将以下代码添加到文件中:
FROM php:7.2-fpm
# Copy composer.lock and composer.json
COPY composer.lock composer.json /var/www/
# Set working directory
WORKDIR /var/www
# Install dependencies
RUN apt-get update && apt-get install -y \
build-essential \
libpng-dev \
libjpeg62-turbo-dev \
libfreetype6-dev \
locales \
zip \
jpegoptim optipng pngquant gifsicle \
vim \
unzip \
git \
curl
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
# Install extensions
RUN docker-php-ext-install pdo_mysql mbstring zip exif pcntl
RUN docker-php-ext-configure gd --with-gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ --with-png-dir=/usr/include/
RUN docker-php-ext-install gd
# Install composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
# Add user for laravel application
RUN groupadd -g 1000 www
RUN useradd -u 1000 -ms /bin/bash -g www www
# Copy existing application directory contents
COPY . /var/www
# Copy existing application directory permissions
COPY --chown=www:www . /var/www
# Change current user to www
USER www
# Expose port 9000 and start php-fpm server
EXPOSE 9000
CMD ["php-fpm"]
First, the Dockerfile creates an image on top of the php:7.2-fpm
Docker image. This is a Debian-based image that has the PHP FastCGI implementation PHP-FPM installed. The file also installs the prerequisite packages for Laravel: mcrypt
, pdo_mysql
, mbstring
, and imagick
with composer
.
首先,Dockerfile在php:7.2-fpm
Docker映像之上创建一个映像 。 这是一个基于Debian的映像,其中安装了PHP FastCGI实现PHP-FPM 。 该文件还为Laravel安装了必备软件包: mcrypt
, pdo_mysql
, mbstring
和imagick
以及composer
。
The RUN
directive specifies the commands to update, install, and configure settings inside the container, including creating a dedicated user and group called www. The WORKDIR
instruction specifies the /var/www
directory as the working directory for the application.
RUN
指令指定用于更新,安装和配置容器内设置的命令,包括创建名为www的专用用户和组。 WORKDIR
指令将/var/www
目录指定为应用程序的工作目录。
Creating a dedicated user and group with restricted permissions mitigates the inherent vulnerability when running Docker containers, which run by default as root. Instead of running this container as root, we’ve created the www user, who has read/write access to the /var/www
folder thanks to the COPY
instruction that we are using with the --chown
flag to copy the application folder’s permissions.
创建具有受限权限的专用用户和组可缓解运行Docker容器(默认情况下以root身份运行)时的固有漏洞。 我们不是创建容器的root用户 ,而是创建了www用户,该用户对/var/www
文件夹具有读/写访问权限,这要归功于COPY
指令,该指令与--chown
标志一起用于复制应用程序文件夹的权限。
Finally, the EXPOSE
command exposes a port in the container, 9000
, for the php-fpm
server. CMD
specifies the command that should run once the container is created. Here, CMD
specifies "php-fpm"
, which will start the server.
最后, EXPOSE
命令在容器9000
公开用于php-fpm
服务器的端口。 CMD
指定在创建容器后应运行的命令。 在这里, CMD
指定了"php-fpm"
,它将启动服务器。
Save the file and exit your editor when you are finished making changes.
完成更改后,保存文件并退出编辑器。
You can now move on to defining your PHP configuration.
现在,您可以继续定义PHP配置。
步骤5 —配置PHP (Step 5 — Configuring PHP)
Now that you have defined your infrastructure in the docker-compose
file, you can configure the PHP service to act as a PHP processor for incoming requests from Nginx.
既然您已经在docker-compose
文件中定义了基础架构,就可以将PHP服务配置为充当来自Nginx的传入请求PHP处理器。
To configure PHP, you will create the local.ini
file inside the php
folder. This is the file that you bind-mounted to /usr/local/etc/php/conf.d/local.ini
inside the container in Step 2. Creating this file will allow you to override the default php.ini
file that PHP reads when it starts.
要配置PHP,您将在php
文件夹中创建local.ini
文件。 这是您在步骤2中绑定安装到容器内的/usr/local/etc/php/conf.d/local.ini
的文件。创建此文件将使您能够覆盖PHP读取的默认php.ini
文件。当它开始的时候。
Create the php
directory:
创建php
目录:
- mkdir ~/laravel-app/php mkdir〜/ laravel-app / php
Next, open the local.ini
file:
接下来,打开local.ini
文件:
- nano ~/laravel-app/php/local.ini 纳米〜/ laravel-app / php / local.ini
To demonstrate how to configure PHP, we’ll add the following code to set size limitations for uploaded files:
为了演示如何配置PHP,我们将添加以下代码来设置上传文件的大小限制:
upload_max_filesize=40M
post_max_size=40M
The upload_max_filesize
and post_max_size
directives set the maximum allowed size for uploaded files, and demonstrate how you can set php.ini
configurations from your local.ini
file. You can put any PHP-specific configuration that you want to override in the local.ini
file.
upload_max_filesize
和post_max_size
指令设置了上载文件的最大允许大小,并演示了如何从local.ini
文件设置php.ini
配置。 您可以将要覆盖的任何特定于PHP的配置放入local.ini
文件中。
Save the file and exit your editor.
保存文件并退出编辑器。
With your PHP local.ini
file in place, you can move on to configuring Nginx.
放置好PHP local.ini
文件后,您就可以继续配置Nginx。
第6步—配置Nginx (Step 6 — Configuring Nginx)
With the PHP service configured, you can modify the Nginx service to use PHP-FPM as the FastCGI server to serve dynamic content. The FastCGI server is based on a binary protocol for interfacing interactive programs with a web server. For more information, please refer to this article on Understanding and Implementing FastCGI Proxying in Nginx.
配置了PHP服务后,您可以修改Nginx服务以将PHP-FPM用作FastCGI服务器来提供动态内容。 FastCGI服务器基于二进制协议,用于将交互程序与Web服务器接口。 有关更多信息,请参考有关在Nginx中理解和实现FastCGI代理的文章。
To configure Nginx, you will create an app.conf
file with the service configuration in the ~/laravel-app/nginx/conf.d/
folder.
要配置Nginx,您将在~/laravel-app/nginx/conf.d/
文件夹中创建一个带有服务配置的app.conf
文件。
First, create the nginx/conf.d/
directory:
首先,创建nginx/conf.d/
目录:
- mkdir -p ~/laravel-app/nginx/conf.d mkdir -p〜/ laravel-app / nginx / conf.d
Next, create the app.conf
configuration file:
接下来,创建app.conf
配置文件:
- nano ~/laravel-app/nginx/conf.d/app.conf 纳米〜/ laravel-app / nginx / conf.d / app.conf
Add the following code to the file to specify your Nginx configuration:
将以下代码添加到文件中以指定您的Nginx配置:
server {
listen 80;
index index.php index.html;
error_log /var/log/nginx/error.log;
access_log /var/log/nginx/access.log;
root /var/www/public;
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass app: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 / {
try_files $uri $uri/ /index.php?$query_string;
gzip_static on;
}
}
The server block defines the configuration for the Nginx web server with the following directives:
服务器块使用以下指令定义Nginx Web服务器的配置:
listen
: This directive defines the port on which the server will listen to incoming requests.listen
:此伪指令定义服务器将在其上侦听传入请求的端口。error_log
andaccess_log
: These directives define the files for writing logs.error_log
和access_log
:这些指令定义用于写入日志的文件。root
: This directive sets the root folder path, forming the complete path to any requested file on the local file system.root
:此伪指令设置根文件夹路径,形成本地文件系统上任何请求的文件的完整路径。
In the php
location block, the fastcgi_pass
directive specifies that the app
service is listening on a TCP socket on port 9000
. This makes the PHP-FPM server listen over the network rather than on a Unix socket. Though a Unix socket has a slight advantage in speed over a TCP socket, it does not have a network protocol and thus skips the network stack. For cases where hosts are located on one machine, a Unix socket may make sense, but in cases where you have services running on different hosts, a TCP socket offers the advantage of allowing you to connect to distributed services. Because our app
container is running on a different host from our webserver
container, a TCP socket makes the most sense for our configuration.
在php
location块中, fastcgi_pass
指令指定app
服务正在侦听端口9000
上的TCP套接字。 这使得PHP-FPM服务器通过网络而不是在Unix套接字上进行侦听。 尽管Unix套接字在速度上比TCP套接字略有优势,但它没有网络协议,因此会跳过网络堆栈。 对于主机位于一台计算机上的情况,可以使用Unix套接字,但是对于在不同主机上运行的服务,TCP套接字具有的优势是可以连接到分布式服务。 由于我们的app
容器与webserver
容器在不同的主机上运行,因此TCP套接字最适合我们的配置。
Save the file and exit your editor when you are finished making changes.
完成更改后,保存文件并退出编辑器。
Thanks to the bind mount you created in Step 2, any changes you make inside the nginx/conf.d/
folder will be directly reflected inside the webserver
container.
由于您在步骤2中创建了绑定安装,因此您在nginx/conf.d/
文件夹中进行的任何更改都将直接反映在webserver
容器中。
Next, let’s look at our MySQL settings.
接下来,让我们看看我们MySQL设置。
第7步-配置MySQL (Step 7 — Configuring MySQL)
With PHP and Nginx configured, you can enable MySQL to act as the database for your application.
配置了PHP和Nginx后,可以使MySQL充当应用程序的数据库。
To configure MySQL, you will create the my.cnf
file in the mysql
folder. This is the file that you bind-mounted to /etc/mysql/my.cnf
inside the container in Step 2. This bind mount allows you to override the my.cnf
settings as and when required.
要配置MySQL,您将在mysql
文件夹中创建my.cnf
文件。 这是你压圈安装到文件/etc/mysql/my.cnf
容器内部在步骤2中此绑定安装允许覆盖所述my.cnf
如需要时和设置。
To demonstrate how this works, we’ll add settings to the my.cnf
file that enable the general query log and specify the log file.
为了演示其工作原理,我们将在my.cnf
文件中添加设置以启用常规查询日志并指定日志文件。
First, create the mysql
directory:
首先,创建mysql
目录:
- mkdir ~/laravel-app/mysql mkdir〜/ laravel-app / mysql
Next, make the my.cnf
file:
接下来,制作my.cnf
文件:
- nano ~/laravel-app/mysql/my.cnf 纳米〜/ laravel-app / mysql / my.cnf
In the file, add the following code to enable the query log and set the log file location:
在文件中,添加以下代码以启用查询日志并设置日志文件位置:
[mysqld]
general_log = 1
general_log_file = /var/lib/mysql/general.log
This my.cnf
file enables logs, defining the general_log
setting as 1
to allow general logs. The general_log_file
setting specifies where the logs will be stored.
此my.cnf
文件启用日志,并将general_log
设置定义为1
以允许常规日志。 general_log_file
设置指定日志的存储位置。
Save the file and exit your editor.
保存文件并退出编辑器。
Our next step will be to start the containers.
我们的下一步将是启动容器。
步骤8 —修改环境设置并运行容器 (Step 8 — Modifying Environment Settings and Running the Containers)
Now that you have defined all of your services in your docker-compose
file and created the configuration files for these services, you can start the containers. As a final step, though, we will make a copy of the .env.example
file that Laravel includes by default and name the copy .env
, which is the file Laravel expects to define its environment:
既然您已经在docker-compose
文件中定义了所有服务并创建了这些服务的配置文件,则可以启动容器。 不过,作为最后一步,我们将复制.env.example
默认包含的.env.example
文件,并将其命名为.env
副本,这是Laravel希望定义其环境的文件:
- cp .env.example .env cp .env.example .env
You can now modify the .env
file on the app
container to include specific details about your setup.
现在,您可以修改app
容器上的.env
文件,以包含有关设置的特定详细信息。
Open the file using nano
or your text editor of choice:
使用nano
或您选择的文本编辑器打开文件:
- nano .env 纳米.env
Find the block that specifies DB_CONNECTION
and update it to reflect the specifics of your setup. You will modify the following fields:
查找指定DB_CONNECTION
的块,并对其进行更新以反映设置的细节。 您将修改以下字段:
DB_HOST
will be yourdb
database container.DB_HOST
将是您的db
数据库容器。DB_DATABASE
will be thelaravel
database.DB_DATABASE
将是laravel
数据库。DB_USERNAME
will be the username you will use for your database. In this case, we will uselaraveluser
.DB_USERNAME
将是您将用于数据库的用户名。 在这种情况下,我们将使用laraveluser
。DB_PASSWORD
will be the secure password you would like to use for this user account.DB_PASSWORD
将是您要用于此用户帐户的安全密码。
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=laraveluser
DB_PASSWORD=your_laravel_db_password
Save your changes and exit your editor.
保存更改并退出编辑器。
With all of your services defined in your docker-compose
file, you just need to issue a single command to start all of the containers, create the volumes, and set up and connect the networks:
在docker-compose
文件中定义了所有服务之后,您只需发出一个命令即可启动所有容器,创建卷以及建立和连接网络:
- docker-compose up -d docker-compose up -d
When you run docker-compose up
for the first time, it will download all of the necessary Docker images, which might take a while. Once the images are downloaded and stored in your local machine, Compose will create your containers. The -d
flag daemonizes the process, running your containers in the background.
首次运行docker-compose up
时,它将下载所有必要的Docker映像,这可能需要一段时间。 一旦下载了图像并将其存储在本地计算机中,Compose将创建您的容器。 -d
标志守护进程,在后台运行容器。
Once the process is complete, use the following command to list all of the running containers:
该过程完成后,使用以下命令列出所有正在运行的容器:
- docker ps 码头工人ps
You will see the following output with details about your app
, webserver
, and db
containers:
您将看到以下输出,其中包含有关您的app
, webserver
和db
容器的详细信息:
Output
CONTAINER ID NAMES IMAGE STATUS PORTS
c31b7b3251e0 db mysql:5.7.22 Up 2 seconds 0.0.0.0:3306->3306/tcp
ed5a69704580 app digitalocean.com/php Up 2 seconds 9000/tcp
5ce4ee31d7c0 webserver nginx:alpine Up 2 seconds 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp
The CONTAINER ID
in this output is a unique identifier for each container, while NAMES
lists the service name associated with each. You can use both of these identifiers to access the containers. IMAGE
defines the image name for each container, while STATUS
provides information about the container’s state: whether it’s running, restarting, or stopped.
此输出中的CONTAINER ID
是每个容器的唯一标识符,而NAMES
列出了与每个容器相关的服务名称。 您可以使用这两个标识符来访问容器。 IMAGE
定义每个容器的映像名称,而STATUS
提供有关容器状态的信息:容器是运行,重新启动还是停止。
We’ll now use docker-compose exec
to set the application key for the Laravel application. The docker-compose exec
command allows you to run specific commands in containers.
现在,我们将使用docker-compose exec
设置Laravel应用程序的应用程序密钥。 docker-compose exec
命令允许您在容器中运行特定命令。
The following command will generate a key and copy it to your .env
file, ensuring that your user sessions and encrypted data remain secure:
以下命令将生成一个密钥并将其复制到您的.env
文件中,以确保您的用户会话和加密数据保持安全:
docker-compose exec app php artisan key:generate
docker-compose exec app php artisan key:generate
You now have the environment settings required to run your application. To cache these settings into a file, which will boost your application’s load speed, run:
现在,您具有运行应用程序所需的环境设置。 要将这些设置缓存到文件中,这将提高应用程序的加载速度,请运行:
docker-compose exec app php artisan config:cache
docker-compose exec app php artisan config:cache
Your configuration settings will be loaded into /var/www/bootstrap/cache/config.php
on the container.
您的配置设置将被加载到容器上的/var/www/bootstrap/cache/config.php
中。
As a final step, visit http://your_server_ip
in the browser. You will see the following home page for your Laravel application:
最后一步,在浏览器中访问http:// your_server_ip
。 您将为您的Laravel应用程序看到以下主页:
With your containers running and your configuration information in place, you can move on to configuring your user information for the laravel
database on the db
container.
在容器运行并且配置信息就位之后,您可以继续在db
容器上配置laravel
数据库的用户信息。
第9步-为MySQL创建用户 (Step 9 — Creating a User for MySQL)
The default MySQL installation only creates the root administrative account, which has unlimited privileges on the database server. In general, it’s better to avoid using the root administrative account when interacting with the database. Instead, let’s create a dedicated database user for our application’s Laravel database.
默认MySQL安装仅创建根管理帐户,该帐户在数据库服务器上具有无限特权。 通常,最好在与数据库进行交互时避免使用根管理帐户。 相反,让我们为应用程序的Laravel数据库创建一个专用的数据库用户。
To create a new user, execute an interactive bash shell on the db
container with docker-compose exec
:
要创建新用户,请使用docker-compose exec
在db
容器上执行交互式bash shell:
docker-compose exec db bash
docker-compose exec db bash
Inside the container, log into the MySQL root administrative account:
在容器内,登录到MySQL 根管理帐户:
- mysql -u root -p mysql -u root -p
You will be prompted for the password you set for the MySQL root account during installation in your docker-compose
file.
系统会提示您在docker-compose
文件中输入在安装过程中为MySQL 根帐户设置的密码。
Start by checking for the database called laravel
, which you defined in your docker-compose
file. Run the show databases
command to check for existing databases:
首先检查您在laravel
docker-compose
文件中定义的名为laravel
的数据库。 运行show databases
命令以检查现有数据库:
- show databases; 显示数据库;
You will see the laravel
database listed in the output:
您将在输出中看到laravel
数据库:
Output
+--------------------+
| Database |
+--------------------+
| information_schema |
| laravel |
| mysql |
| performance_schema |
| sys |
+--------------------+
5 rows in set (0.00 sec)
Next, create the user account that will be allowed to access this database. Our username will be laraveluser
, though you can replace this with another name if you’d prefer. Just be sure that your username and password here match the details you set in your .env
file in the previous step:
接下来,创建将被允许访问该数据库的用户帐户。 我们的用户名将为laraveluser
,不过您可以根据laraveluser
将其替换为另一个名称。 只要确保您的用户名和密码与您在上一步中在.env
文件中设置的详细信息匹配.env
:
GRANT ALL ON laravel.* TO 'laraveluser'@'%' IDENTIFIED BY 'your_laravel_db_password';
将所有内容授予laravel。*致' laraveluser '@'%'由' your_laravel_db_password '标识;
Flush the privileges to notify the MySQL server of the changes:
刷新特权以将更改通知MySQL服务器:
- FLUSH PRIVILEGES; 冲洗特权;
Exit MySQL:
退出MySQL:
- EXIT; 出口;
Finally, exit the container:
最后,退出容器:
- exit 出口
You have configured the user account for your Laravel application database and are ready to migrate your data and work with the Tinker console.
您已经为Laravel应用程序数据库配置了用户帐户,并准备迁移数据并使用Tinker控制台。
步骤10 —迁移数据并使用Tinker Console (Step 10 — Migrating Data and Working with the Tinker Console)
With your application running, you can migrate your data and experiment with the tinker
command, which will initiate a PsySH console with Laravel preloaded. PsySH is a runtime developer console and interactive debugger for PHP, and Tinker is a REPL specifically for Laravel. Using the tinker
command will allow you to interact with your Laravel application from the command line in an interactive shell.
随着应用程序的运行,您可以迁移数据并尝试使用tinker
命令,该命令将启动一个预加载Laravel的PsySH控制台。 PsySH是用于PHP的运行时开发人员控制台和交互式调试器,而Tinker是专门用于Laravel的REPL。 使用tinker
命令将使您可以在交互式Shell中从命令行与Laravel应用程序进行交互。
First, test the connection to MySQL by running the Laravel artisan migrate
command, which creates a migrations
table in the database from inside the container:
首先,通过运行Laravel artisan migrate
migrations
命令测试与MySQL的连接,该命令从容器内部在数据库中创建一个migrations
表:
docker-compose exec app php artisan migrate
docker-compose exec app php artisan migration
This command will migrate the default Laravel tables. The output confirming the migration will look like this:
该命令将迁移默认的Laravel表。 确认迁移的输出如下所示:
Output
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table
Once the migration is complete, you can run a query to check if you are properly connected to the database using the tinker
command:
迁移完成后,您可以运行查询以使用tinker
命令检查是否正确连接到数据库:
docker-compose exec app php artisan tinker
docker-compose exec app php artisan tinker
Test the MySQL connection by getting the data you just migrated:
通过获取刚迁移的数据来测试MySQL连接:
- \DB::table('migrations')->get(); \ DB :: table('migrations')-> get();
You will see output that looks like this:
您将看到如下所示的输出:
Output
=> Illuminate\Support\Collection {#2856
all: [
{#2862
+"id": 1,
+"migration": "2014_10_12_000000_create_users_table",
+"batch": 1,
},
{#2865
+"id": 2,
+"migration": "2014_10_12_100000_create_password_resets_table",
+"batch": 1,
},
],
}
You can use tinker
to interact with your databases and to experiment with services and models.
您可以使用tinker
程序与您的数据库进行交互,并尝试使用服务和模型。
With your Laravel application in place, you are ready for further development and experimentation.
有了Laravel应用程序,您就可以进行进一步的开发和实验了。
结论 (Conclusion)
You now have a LEMP stack application running on your server, which you’ve tested by accessing the Laravel welcome page and creating MySQL database migrations.
现在,您的服务器上运行了一个LEMP堆栈应用程序,已通过访问Laravel欢迎页面并创建MySQL数据库迁移进行了测试。
Key to the simplicity of this installation is Docker Compose, which allows you to create a group of Docker containers, defined in a single file, with a single command. If you would like to learn more about how to do CI with Docker Compose, take a look at How To Configure a Continuous Integration Testing Environment with Docker and Docker Compose on Ubuntu 16.04. If you want to streamline your Laravel application deployment process then How to Automatically Deploy Laravel Applications with Deployer on Ubuntu 16.04 will be a relevant resource.
简化此安装的关键是Docker Compose,它允许您使用单个命令创建一组在单个文件中定义的Docker容器。 如果您想了解有关如何使用Docker Compose进行CI的更多信息,请查看如何在Ubuntu 16.04上使用Docker和Docker Compose配置连续集成测试环境 。 如果您想简化Laravel应用程序的部署过程,那么如何在Ubuntu 16.04上使用Deployer自动部署Laravel应用程序将是一个相关资源。