docker compose构建多容器应用(Nginx+PHP+MySQL+Redis)

首先安装compose

#下载并移动到/usr/local/bin目录下

curl -L “https://github.com/docker/compose/releases/download/1.23.1/docker-compose-$(uname -s)-$(uname -m)” \

-o /usr/local/bin/docker-compose

#赋予可执行权限

chmod +x /usr/local/bin/docker-compose

然后执行docker-compose –version 如果能看显示对应的版本号说明安装成功

再一个空目录下创建nginx 和php两个目录,首先进入nginx目录并创建一个Dockerfile文件

cd nginx
vi Dockerfile

在Dockerfile文件中写入如下指令

FROM nginx:latest

COPY default.conf /etc/nginx/conf.d/default.conf

保存Dockerfile文件后再创建一个default.conf内容为

#以下内容仅供参考,请按实际环境定制

server {

listen 80;

server_name localhost;

root /usr/share/nginx/html;

index index.html index.htm index.php;

location ~ \.php$ {

fastcgi_pass php-fpm:9000;

fastcgi_index index.php;

fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/$fastcgi_script_name;

include fastcgi_params;

}

}

保存文件后再执行 cd ../php 进入php目录 编辑Dockerfile文件(主要增加了一些常用扩展,请按实际情况定制) 内容如下

FROM php:7.3-fpm

RUN docker-php-ext-install pdo pdo_mysql mysqli \

&& pecl install redis-4.2.0 && docker-php-ext-enable redis

然后保存,cd .. 回到外层目录创建docker-compose.yml文件

vi docker-compose.yml 并键入如下内容

version: ‘3’
networks:
dev-net:
driver: bridge
services:
mysql:
image: mysql:latest
command: –default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: root
networks:
– dev-net
nginx:
build: nginx
restart: always
ports:
– 80:80
volumes:
– /home/wwwroot/default/:/usr/share/nginx/html
depends_on:
– mysql
– redis
– php-fpm
networks:
– dev-net
php-fpm:
build: php
volumes:
– /home/wwwroot/default/:/usr/share/nginx/html
networks:
– dev-net
redis:
image: redis:latest
networks:
– dev-net

保存后执行

docker-compose up -d

等待完成自动构建即可