docker 安装 nginx+php7+mysql5.7 运行环境。

docker 之基于Dockerfile构建 Nginx+ php7
**前言**

本文是将Nginx 和PHP7安装在不同容器,同–link实现交互通信,网上查有些资料将LNMP装在一个容器,我认为装在一起固然简单一些,但不够灵活(纯个人看法,有不同观点,欢迎回复)。

脚本更新请在git中查看 https://gitlab.scjtqs.com:58543/scjtqs/docker_lnmp

或者直接

docker pull scjtqs/nginx
docker pull scjtqs/php-fpm

 

系统环境:CentOS Linux release 7.4.1708
一、构建nginx
1、创建目录/var/docker/

“`
mkdir -p /var/docker1
“`

GITLAB拉取相关配置文件 ,将nginx文件夹复制到/var/docker/下。
/var/docker/nginx 目录结构为

“`
[root@idddfwetddffa nginx]# ll
-rw-r–r– 1 root root 682 Mar 20 22:19 Dockerfile
-rw-r–r– 1 root root 2572 Mar 20 16:30 nginx.conf
-rw-r–r– 1 root root 8011 Mar 20 22:17 supervisord.conf
-rw-r–r– 1 root root 351 Mar 20 22:19 www.conf
“`

查看Dockerfile (注意,Dockerfile名字第一个字母必须为大写)

“`
FROM centos:7.4.1708
MAINTAINER [email protected]
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
#安装YUM源
RUN rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
RUN rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
#安装nginx
RUN yum -y install gcc gcc-c++ \
openssl openssl-devel \
zlib zlib-devel \
nginx supervisor
EXPOSE 80
RUN rm -rf /var/lib/yum/history/*.sqlite &&\
rm -rf /var/cache/yum
RUN rm -f /etc/supervisord.conf
COPY supervisord.conf /etc/
#COPY www.conf /etc/nginx/conf.d/
COPY nginx.conf /etc/nginx/
#CMD [“/usr/sbin/nginx”,”-g”,”daemon off;”]
CMD [“/usr/bin/supervisord”,”-c”,”/etc/supervisord.conf”]
“`

nginx.conf

“`
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
worker_connections 1024;
}

http {
log_format main ‘remote_addr –remote_user [time_local] “request” ‘
statusbody_bytes_sent “http_referer” ‘
‘”
http_user_agent” “http_x_forwarded_for”‘;

access_log /var/log/nginx/access.log main;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;

include /etc/nginx/mime.types;
default_type application/octet-stream;

# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;

server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;

location / {
}

error_page 404 /404.html;
location = /40x.html {
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}

# Settings for a TLS enabled server.
#
# server {
# listen 443 ssl http2 default_server;
# listen [::]:443 ssl http2 default_server;
# server_name _;
# root /usr/share/nginx/html;
#
# ssl_certificate “/etc/pki/nginx/server.crt”;
# ssl_certificate_key “/etc/pki/nginx/private/server.key”;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 10m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
#
# # Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
#
# location / {
# }
#
# error_page 404 /404.html;
# location = /40x.html {
# }
#
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }

}
“`

supervisord.conf (nginx进程管理软件)

“`
; Sample supervisor config file.

[unix_http_server]
file=/var/run/supervisor/supervisor.sock ; (the path to the socket file)
;chmod=0700 ; sockef file mode (default 0700)
;chown=nobody:nogroup ; socket file uid:gid owner
;username=user ; (default is no username (open server))
;password=123 ; (default is no password (open server))

;[inet_http_server] ; inet (TCP) server disabled by default
;port=127.0.0.1:9001 ; (ip_address:port specifier, *:port for all iface)
;username=user ; (default is no username (open server))
;password=123 ; (default is no password (open server))

[supervisord]
logfile=/var/log/supervisor/supervisord.log ; (main log file;defaultCWD/supervisord.log)
logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10 ; (num of main logfile rotation backups;default 10)
loglevel=info ; (log level;default info; others: debug,warn,trace)
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=true ; (start in foreground if true;default false)
minfds=1024 ; (min. avail startup file descriptors;default 1024)
minprocs=200 ; (min. avail process descriptors;default 200)
;umask=022 ; (process file creation umask;default 022)
;user=chrism ; (default is current user, required if root)
;identifier=supervisor ; (supervisord identifier, default is ‘supervisor’)
;directory=/tmp ; (default is not to cd during start)
;nocleanup=true ; (don’t clean up tempfiles at start;default false)
;childlogdir=/tmp ; (‘AUTO’ child log dir, default TEMP)
;environment=KEY=value ; (key value pairs to add to environment)
;strip_ansi=false ; (strip ansi escape codes in logs; def. false)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock ; use a unix:// URL for a unix socket
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket
;username=chris ; should be same as http_username if set
;password=123 ; should be same as http_password if set
;prompt=mysupervisor ; cmd line prompt (default “supervisor”)
;history_file=~/.sc_history ; use readline history if available

; The below sample program section shows all possible program subsection values,
; create one or more ‘real’ program: sections to be able to control them under
; supervisor.

;[program:theprogramname]
;command=/bin/cat ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1 ; number of processes copies to start (def 1)
;directory=/tmp ; directory to cwd to before exec (def no cwd)
;umask=022 ; umask for process (default None)
;priority=999 ; the relative start priority (default 999)
;autostart=true ; start at supervisord start (default: true)
;autorestart=true ; retstart at unexpected quit (default: true)
;startsecs=10 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; ‘expected’ exit codes for process (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_capture_maxbytes=1MB ; number of bytes in ‘capturemode’ (default 0)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10 ; # of stderr logfile backups (default 10)
;stderr_capture_maxbytes=1MB ; number of bytes in ‘capturemode’ (default 0)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions (def no adds)
;serverurl=AUTO ; override serverurl computation (childutils)

; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more ‘real’
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.

;[eventlistener:theeventlistenername]
;command=/bin/eventlistener ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1 ; number of processes copies to start (def 1)
;events=EVENT ; event notif. types to subscribe to (req’d)
;buffer_size=10 ; event buffer queue size (default 10)
;directory=/tmp ; directory to cwd to before exec (def no cwd)
;umask=022 ; umask for process (default None)
;priority=-1 ; the relative start priority (default -1)
;autostart=true ; start at supervisord start (default: true)
;autorestart=unexpected ; restart at unexpected quit (default: unexpected)
;startsecs=10 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; ‘expected’ exit codes for process (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups ; # of stderr logfile backups (default 10)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions
;serverurl=AUTO ; override serverurl computation (childutils)

; The below sample group section shows all possible group values,
; create one or more ‘real’ group: sections to create “heterogeneous”
; process groups.

;[group:thegroupname]
;programs=progname1,progname2 ; each refers to ‘x’ in [program:x] definitions
;priority=999 ; the relative start priority (default 999)

; The [include] section can just contain the “files” setting. This
; setting can list multiple files (separated by whitespace or
; newlines). It can also contain wildcards. The filenames are
; interpreted as relative to this file. Included files *cannot*
; include files themselves.

[program:nginx]
command=/usr/sbin/nginx -g ‘daemon off;’

[include]
files = supervisord.d/*.ini
“`

而对于nginx来说:
daemon off表示将后台运行关闭了,运行在前台,supervisord监控前台运行的程序。

www.conf

“`
server {
listen 80;
server_name wx.scjtqs.com;
root /var/www;
index index.htm index.html index.php;

location ~ \.php {
root /var/www;
fastcgi_pass php:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME document_rootfastcgi_script_name;
include fastcgi_params;
}
}
“`

将 wx.scjtqs.com 改成你自己的域名

2、 开始进行构建nginx:

在 /var/docker/nginx 下执行

“`
docker build -t php .
“`

二、构建 php7.1
1、同上将php文件复制到 /var/docker下

目录为

“`
-rw-r–r– 1 root root 1229 Mar 20 22:33 Dockerfile
-rw-r–r– 1 root root 8052 Mar 20 22:33 supervisord.conf
“`

Dockerfile

“`
FROM centos:7.4.1708
MAINTAINER [email protected]
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
#安装YUM源
RUN yum -y install epel-release
RUN rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
#安装php-fpm
RUN yum -y install gcc gcc-c++ nginx \
openssl openssl-devel \
zlib zlib-devel \
php71w-xml \
php71w-gd \
php71w-cli \
php71w-fpm \
php71w-pear \
php71w-mysqlnd \
php71w-devel \
php71w-mcrypt \
php71w-mbstring \
php71w-common \
php71w-process \
php71w-pdo \
php71w-opcache \
php71w-intl \
php71w-pecl-imagick \
php71w-pecl-redis \
php71w-pecl-memcached \
php71w-pecl-mongodb
EXPOSE 9000
RUN sed -i ‘s@daemonize = yes@daemonize = no@g’ /etc/php-fpm.conf
RUN sed -i -e ‘s@listen = 127.0.0.1:9000@listen = 0.0.0.0:9000@g’ /etc/php-fpm.d/www.conf
RUN sed -i -e ‘[email protected]_clients = 127.0.0.1@;listen.allowed_clients = 127.0.0.1@g’ /etc/php-fpm.d/www.conf
#修改 php的用户和用户组以 nginx的用户来跑,满足权限问题
RUN sed -i -e ‘s@user = apache@user = nginx@g’ /etc/php-fpm.d/www.conf
RUN sed -i -e ‘s@group = apache@group = nginx@g’ /etc/php-fpm.d/www.conf
COPY pecl-memcache WORKDIR/pecl-memcache

RUN cd WORKDIR/pecl-memcache && /usr/bin/phpize && ./configure && make && make install
COPY memcache.ini /etc/php.d/
COPY memcache.ini /etc/php-zts.d/

#安装supervisor 并修复 php的session权限
RUN yum -y install supervisor && \
mkdir -p /var/lib/php/session && \
chown -R nginx:nginx /var/lib/php/session

RUN rm -rf /var/lib/yum/history/*.sqlite &&\
rm -rf /var/cache/yum &&\
rm -rf WORKDIR/pecl-memcache
RUN rm -f /etc/supervisord.conf
ADD supervisord.conf /etc/
#CMD [“/usr/sbin/init”]
#CMD [“/usr/sbin/php-fpm”]
CMD [“/usr/bin/supervisord”,”-c”,”/etc/supervisord.conf”]
“`

supervisord.conf

“`
; Sample supervisor config file.

[unix_http_server]
file=/var/run/supervisor/supervisor.sock ; (the path to the socket file)
;chmod=0700 ; sockef file mode (default 0700)
;chown=nobody:nogroup ; socket file uid:gid owner
;username=user ; (default is no username (open server))
;password=123 ; (default is no password (open server))

;[inet_http_server] ; inet (TCP) server disabled by default
;port=127.0.0.1:9001 ; (ip_address:port specifier, *:port for all iface)
;username=user ; (default is no username (open server))
;password=123 ; (default is no password (open server))

[supervisord]
logfile=/var/log/supervisor/supervisord.log ; (main log file;default CWD/supervisord.log)
logfile_maxbytes=50MB ; (max main logfile bytes b4 rotation;default 50MB)
logfile_backups=10 ; (num of main logfile rotation backups;default 10)
loglevel=info ; (log level;default info; others: debug,warn,trace)
pidfile=/var/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid)
nodaemon=true ; (start in foreground if true;default false)
minfds=1024 ; (min. avail startup file descriptors;default 1024)
minprocs=200 ; (min. avail process descriptors;default 200)
;umask=022 ; (process file creation umask;default 022)
;user=chrism ; (default is current user, required if root)
;identifier=supervisor ; (supervisord identifier, default is ‘supervisor’)
;directory=/tmp ; (default is not to cd during start)
;nocleanup=true ; (don’t clean up tempfiles at start;default false)
;childlogdir=/tmp ; (‘AUTO’ child log dir, default
TEMP)
;environment=KEY=value ; (key value pairs to add to environment)
;strip_ansi=false ; (strip ansi escape codes in logs; def. false)

; the below section must remain in the config file for RPC
; (supervisorctl/web interface) to work, additional interfaces may be
; added by defining them in separate rpcinterface: sections
[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///var/run/supervisor/supervisor.sock ; use a unix:// URL for a unix socket
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket
;username=chris ; should be same as http_username if set
;password=123 ; should be same as http_password if set
;prompt=mysupervisor ; cmd line prompt (default “supervisor”)
;history_file=~/.sc_history ; use readline history if available

; The below sample program section shows all possible program subsection values,
; create one or more ‘real’ program: sections to be able to control them under
; supervisor.

;[program:theprogramname]
;command=/bin/cat ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1 ; number of processes copies to start (def 1)
;directory=/tmp ; directory to cwd to before exec (def no cwd)
;umask=022 ; umask for process (default None)
;priority=999 ; the relative start priority (default 999)
;autostart=true ; start at supervisord start (default: true)
;autorestart=true ; retstart at unexpected quit (default: true)
;startsecs=10 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; ‘expected’ exit codes for process (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_capture_maxbytes=1MB ; number of bytes in ‘capturemode’ (default 0)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups=10 ; # of stderr logfile backups (default 10)
;stderr_capture_maxbytes=1MB ; number of bytes in ‘capturemode’ (default 0)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions (def no adds)
;serverurl=AUTO ; override serverurl computation (childutils)

; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more ‘real’
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.

;[eventlistener:theeventlistenername]
;command=/bin/eventlistener ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1 ; number of processes copies to start (def 1)
;events=EVENT ; event notif. types to subscribe to (req’d)
;buffer_size=10 ; event buffer queue size (default 10)
;directory=/tmp ; directory to cwd to before exec (def no cwd)
;umask=022 ; umask for process (default None)
;priority=-1 ; the relative start priority (default -1)
;autostart=true ; start at supervisord start (default: true)
;autorestart=unexpected ; restart at unexpected quit (default: unexpected)
;startsecs=10 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; ‘expected’ exit codes for process (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups ; # of stderr logfile backups (default 10)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A=1,B=2 ; process environment additions
;serverurl=AUTO ; override serverurl computation (childutils)

; The below sample group section shows all possible group values,
; create one or more ‘real’ group: sections to create “heterogeneous”
; process groups.

;[group:thegroupname]
;programs=progname1,progname2 ; each refers to ‘x’ in [program:x] definitions
;priority=999 ; the relative start priority (default 999)

; The [include] section can just contain the “files” setting. This
; setting can list multiple files (separated by whitespace or
; newlines). It can also contain wildcards. The filenames are
; interpreted as relative to this file. Included files *cannot*
; include files themselves.

[program:php-fpm]
;command=bash -c “sleep 1 && systemctl start php-fpm”
command=/usr/sbin/php-fpm

[include]
files = supervisord.d/*.ini
“`

nodaemon=true
关闭后台运行。

[program:php-fpm]
command=/usr/sbin/php-fpm
增加启动php-fpm

2、构建php7.1

“`
docker build -t nginx .
“`

三、查看生成的镜像

四、利用构建的镜像启动php、nginx服务 以及mysql 服务
运行 mysql5.7

-v 里面的文件位置请替换成自己的目录地址
==
“`
sudo docker pull mysql:5.7

#–restart=always 自动启动
sudo docker run –name=mysql –restart=always -p 3307:3306 -e MYSQL_ROOT_PASSWORD=scjtqs -v /Users/apple/Workspace/data/mysql/data:/var/lib/mysql -v /Users/apple/Workspace/data/mysql/conf:/etc/mysql/conf.d -d mysql:5.7
“`
运行php

“`
sudo docker run –name=php –restart=always -p 9000:9000 -v /Users/apple/Workspace/tmp/www:/var/www/html –link=mysql:db -d php
“`

记住加 -v /var/www:/var/www 即把宿主主机目录/var/www 映射到容器 /var/www ,如果不设置会出现 file not found的错误

“`
sudo docker run –name=nginx –restart=always -p 80:80 -p 443:443 -v /Users/apple/Workspace/tmp/www:/var/www/html -v /Users/apple/Workspace/tmp/docker/nginx/conf.d:/etc/nginx/conf.d –link=php:php -d nginx
“`

这里 –link=php:php 实现了nginx和php容器的互通

五、测试

在/var/www目录下,新建index.php

“`
< ?php
phpinfo();
“`

本文配置文件放在GITLAB 并持续更新:

六、修改php的权限
===

已经修改了php-fpm 以nginx用户运行,因此为了防止没有权限创建文件的情况,需要进入docker的容器内修改一下你的项目目录权限

“`
docker exec -t php /bin/bash
chown -R nginx:nginx /var/www/html
“`

另外,在nginx下的cong.d里面的server里面,需要用到 php:9000来设置fastcgi。

打赏
Bookmark the permalink.
0 0 投票数
文章评分
订阅评论
提醒
guest

0 评论
内联反馈
查看所有评论