原创

[Docker]完整上线一个php+nginx+mysql+redis架构的网站

前言

本文章是我最近将我的站点搭建到docker容器中后,整理出来的,来源于:
docker整站迁移到docker容器中1
docker整站迁移到docker容器中2
docker整站迁移到docker容器中3

使用docker,会让你更加方便的搭建服务环境,不需要管那么细枝末节的问题。

我在腾讯云的轻量云(香港)的机器上进行的本次脚本,如果实践过程有任何错误,请在底下留言,谢谢!

服务器环境信息:

Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                1
On-line CPU(s) list:   0
Thread(s) per core:    1
Core(s) per socket:    1
Socket(s):
           1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 79
Model name:            Intel(R) Xeon(R) CPU E5-26xx v4
Stepping:              1
CPU MHz:               2394.446
BogoMIPS:              4788.89
Hypervisor vendor:     KVM
Virtualization type:   full
L1d cache:             32K
L1i cache:             32K
L2 cache:              4096K
NUMA node0 CPU(s):     0
Flags:                 fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx lm constant_tsc rep_good nopl cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch pti bmi1 avx2 bmi2 rdseed adx xsaveopt
[root@VM-0-11-centos sql]# free -m
              total        used        free      shared  buff/cache   available
Mem:            983         650          91           2         241         188
Swap:             0           0           0
[root@VM-0-11-centos sql]# fdisk -l |grep Disk
Disk /dev/vda: 26.8 GB, 26843545600 bytes, 52428800 sectors
Disk label type: dos
Disk identifier: 0x0009ac89

开整

安装docker

运行这个命令即可:curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

[root@VM-0-11-centos ~]# curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun
# Executing docker install script, commit: 3d8fe77c2c46c5b7571f94b42793905e5b3e42e4
+ sh -c 'yum install -y -q yum-utils'
Package yum-utils-1.1.31-54.el7_8.noarch already installed and latest version
+ sh -c 'yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo'
Loaded plugins: fastestmirror, langpacks
adding repo from: https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
grabbing file https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo
+ '[' stable '!=' stable ']'
+ sh -c 'yum makecache'
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * elrepo: mirror-hk.koddos.net
docker-ce-stable                                                                                          |3.5 kB  00:00:00   
elrepo                                                                                                    |3.0 kB  00:00:00   
epel                                                                                                      |4.7 kB  00:00:00   
extras                                                                                                    |2.9 kB  00:00:00   
nginx                                                                                                     |2.9 kB  00:00:00   
os                                                                                                        |3.6 kB  00:00:00   
updates                                                                                                   |2.9 kB  00:00:00   
(1/17): docker-ce-stable/x86_64/filelists_db                                                              | 23 kB  00:00:00   
(2/17): docker-ce-stable/x86_64/primary_db                                                                | 51 kB  00:00:00   
(3/17): elrepo/filelists_db                                                                               | 29 kB  00:00:00   
(4/17): elrepo/other_db                                                                                   | 26 kB  00:00:00   
(5/17): epel/7/x86_64/prestodelta                                                                         |1.2 kB  00:00:00   
(6/17): docker-ce-stable/x86_64/updateinfo                                                                |  55 B  00:00:00   
(7/17): extras/7/x86_64/filelists_db                                                                      |224 kB  00:00:00   
(8/17): extras/7/x86_64/other_db                                                                          |134 kB  00:00:00   
(9/17): epel/7/x86_64/other_db                                                                            |3.3 MB  00:00:00   
(10/17): epel/7/x86_64/filelists_db                                                                       | 12 MB  00:00:00   
(11/17): os/7/x86_64/filelists_db                                                                         |7.2 MB  00:00:00   
(12/17): docker-ce-stable/x86_64/other_db                                                                 |116 kB  00:00:00   
(13/17): os/7/x86_64/other_db                                                                             |2.6 MB  00:00:00   
(14/17): updates/7/x86_64/filelists_db                                                                    |2.7 MB  00:00:00   
(15/17): updates/7/x86_64/other_db                                                                        |334 kB  00:00:00   
(16/17): nginx/x86_64/other_db                                                                            | 35 kB  00:00:00   
(17/17): nginx/x86_64/filelists_db                                                                        | 81 kB  00:00:00   
Metadata Cache Created
+ '[' -n '' ']'
+ sh -c 'yum install -y -q docker-ce'
warning: /var/cache/yum/x86_64/7/docker-ce-stable/packages/containerd.io-1.4.3-3.1.el7.x86_64.rpm: Header V4 RSA/SHA512 Signature, key ID 621e9f35: NOKEY
Public key for containerd.io-1.4.3-3.1.el7.x86_64.rpm is not installed
Importing GPG key 0x621E9F35:
 Userid     : "Docker Release (CE rpm) <docker@docker.com>"
 Fingerprint: 060a 61c5 1b55 8a7f 742b 77aa c52f eb6b 621e 9f35
 From       : https://mirrors.aliyun.com/docker-ce/linux/centos/gpg
setsebool:  SELinux is disabled.
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker your-user

Remember that you will have to log out and back in for this to take effect!

WARNING: Adding a user to the "docker" group will grant the ability to run
         containers which can be used to obtain root privileges on the
         docker host.
         Refer to https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface
         for more information.
[root@VM-0-11-centos ~]# docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

安装的问题这里不多说,网上教程很多,这篇博文不是为了docker怎么安装做准备的。所以会直接跳过。安装结果使用-v参数来查看docker版本。

[root@web ~]# docker -v
Docker version 20.10.1, build 831ebea

配置docker

  • 启动docker
[root@VM-0-11-centos ~]# systemctl start docker
  • 安装结束需要将docker服务设置为开机启动,很简单,两行命令就行了
[root@VM-0-11-centos ~]# systemctl enable docker
Created symlink from /etc/systemd/system/multi-user.target.wants/docker.service to /usr/lib/systemd/system/docker.service.
  • 如果是国内的机器,还需要配置下docker容器镜像仓库,这样能加速pull的速度。
    比如你可以直接百度搜索:registry-mirrors
网易镜像中心:https://c.163.com/hub#/m/home/ 
daocloud镜像市场:https://hub.daocloud.io/
  • 修改或者创建/etc/docker/daemon.json文件,将底下的地址修改为网易或者daocloud的地址。
# vi /etc/docker/daemon.json
{
    "registry-mirrors": ["https://hub.daocloud.io"]
}

之后执行sudo systemctl daemon-reload以及sudo systemctl restart docker.service,重载docker服务即可。
如果你觉得每次都要输入sudo比较麻烦,可以将当前用户加入到docker组,比如:sudo usermod -aG docker USER_NAME,不过我不推荐这么干。

QA:Ubuntu可能会遇到找不到/etc/docker目录的问题,应该是snap安装docker的方式导致的,可以在/var/snap/docker/current/config/目录中找找。

QA:Ubuntu snap重启docker的方式为:sudo snap restart docker

创建djc8network

推荐使用自定义网络的好处是安全隔离,并且让设置为该网络的容器,可以直接用容器名访问,比较方便。

[root@VM-0-11-centos php]# sudo docker network create -d bridge --subnet 172.25.0.0/16 djc8net
15b7cdb9121c7341bd83c1983f2656c4eff36510fd91e0f9ecb33fc932563240

安装php

我这里使用php8fpm,地址docker hub image layer details

[root@VM-0-11-centos docker]# docker pull php:8-fpm
8-fpm: Pulling from library/php
6ec7b7d162b2: Pull complete 
db606474d60c: Pull complete 
afb30f0cd8e0: Pull complete 
3bb2e8051594: Pull complete 
ebfc042f19c0: Pull complete 
63fdb098c0a6: Pull complete 
10c121fbcee6: Pull complete 
c39b6efd5d79: Pull complete 
86eec37fef5f: Pull complete 
b9f6cb86df11: Pull complete 
Digest: sha256:668edbd434a1aff5f69741910e959289c20c193d7686a7cd1c2335cb55e1cbfb
Status: Downloaded newer image for php:8-fpm
docker.io/library/php:8-fpm

弄下来之后,创建目录,用于存放Dockerfile文件,我建议在根目录中创建一个新的目录,用于存放所有web有关的内容(后续的nginx配置,web内容等),我使用mkdir /www 创建了www目录,位于/下。
cd进入/www/,再创建一个目录,比如php
代码如下:

[root@web ~]# mkdir -p /www/php
[root@web ~]# cd /www/php

创建一个dockerfile文件,比如:touch /www/php/Dockerfile
然后vi编辑这个文件,输入如下的内容

FROM  php:8-fpm

RUN mv /etc/apt/sources.list /etc/apt/sources.list.bak && \
    echo deb http://mirrors.aliyun.com/debian/ stretch main non-free contrib >/etc/apt/sources.list && \
    echo deb-src http://mirrors.aliyun.com/debian/ stretch main non-free contrib >>/etc/apt/sources.list && \
    echo deb http://mirrors.aliyun.com/debian-security stretch/updates main >>/etc/apt/sources.list && \
    echo deb-src http://mirrors.aliyun.com/debian-security stretch/updates main >>/etc/apt/sources.list && \
    echo deb http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib >>/etc/apt/sources.list && \
    echo deb-src http://mirrors.aliyun.com/debian/ stretch-updates main non-free contrib >>/etc/apt/sources.list && \
    echo deb http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib >>/
etc/apt/sources.list && \
    echo deb-src http://mirrors.aliyun.com/debian/ stretch-backports main non-free contrib >>/etc/apt/sources.list
RUN apt-get update

RUN pecl install redis-5.3.2 \
    && docker-php-ext-enable redis \
    && docker-php-ext-install mysqli pdo pdo_mysql

这里不多介绍Dockerfile文件的语法结构,只简单说下。
第一个RUN,执行结束后,会将apt-get的数据源修改为aliyun,加速国内访问,如果你是国外的机器,请取消这一条,否则会很慢。
第二个RUN则是安装必要的依赖,因为我这里使用redis做缓存,使用mysql做持久化,所以需要安装这两个扩展。
在/www/php/目录下,执行docker build -t djc8/php:8fpm .进行镜像构建,这里-t参数代表了这个镜像的名称,重要,后面会用到。


[root@VM-0-11-centos php]# docker build -t djc8/php:8fpm .
Sending build context to Docker daemon   2.56kB
Step 1/2 : FROM  php:8-fpm
 ---> edc6bf79d9ba
Step 2/2 : RUN pecl install redis-5.3.2     && docker-php-ext-enable redis     && docker-php-ext-install mysqli pdo pdo_mysql
 ---> Running in d10bdf9e5d08
downloading redis-5.3.2.tgz ...
Starting to download redis-5.3.2.tgz (266,814 bytes)
........................................................done: 266,814 bytes
29 source files, building
running: phpize
Configuring for:
PHP Api Version:         20200930
Zend Module Api No:      20200930
Zend Extension Api No:   420200930
enable igbinary serializer support? [no] : enable lzf compression support? [no] : enable zstd compression support? [no] : building in /tmp/pear/temp/pear-build-defaultuserJ1XAFr/redis-5.3.2
running: /tmp/pear/temp/redis/configure --with-php-config=/usr/local/bin/php-config --enable-redis-igbinary=no --enable-redis-lzf=no --enable-redis-zstd=no
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for a sed that does not truncate output... /bin/sed
checking for pkg-config... /usr/bin/pkg-config
<---------省略------------------->
If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20200930/
find . -name \*.gcno -o -name \*.gcda | xargs rm -f
find . -name \*.lo -o -name \*.o | xargs rm -f
find . -name \*.la -o -name \*.a | xargs rm -f
find . -name \*.so | xargs rm -f
find . -name .libs -a -type d|xargs rm -rf
rm -f libphp.la      modules/* libs/*
Removing intermediate container d10bdf9e5d08
 ---> ef1328c56ed5
Successfully built ef1328c56ed5
Successfully tagged djc8/php:8fpm

最后看到Successfully built ef1328c56ed5 Successfully tagged djc8/php:8fpm
就代表成功了。

启动php

使用

[root@VM-0-11-centos php]# docker run  -d -p 9000:9000 --name djc8php \
>  --network=djc8net \
>  -v /www/web/public_html:/var/www/html \
>  -v /www/php/conf.d/:/usr/local/etc/php/conf.d \
>  -v /www/php/logs/php_errors.log:/tmp/php_errors.log \
>  -v /www/php/php-fpmconf/:/usr/local/etc/php-fpm.d \
>  djc8/php:8fpm
33716536dc1317c94c2da6721bcd996491fea129a21d26db87b02f79f420cdb3

参数解释:

  • -d 让该容器在后台运行。
  • -p 端口映射,宿主机端口:容器端口
  • --name 容器的名称
  • --network 容器使用的网络
  • -v 挂载卷,宿主机路径:容器路径
    我这里挂载了4个目录,一个是站点的http路径,两个是php配置文件的路径,还有一个是php执行错误的时候的路径。

安装nginx

  • 拉nginx镜像docker pull nginx:1.18.0
[root@VM-0-11-centos php]# docker pull nginx:1.18.0
1.18.0: Pulling from library/nginx
6ec7b7d162b2: Already exists 
43876acb2da3: Pull complete 
7a79edd1e27b: Pull complete 
eea03077c87e: Pull complete 
eba7631b45c5: Pull complete 
Digest: sha256:2eea9f5d6fff078ad6cc6c961ab11b8314efd91fb8480b5d054c7057a619e0c3
Status: Downloaded newer image for nginx:1.18.0
docker.io/library/nginx:1.18.0
  • 创建目录
[root@VM-0-11-centos bin]# mkdir -p /www/nginx/conf/ /www/nginx/conf/vhost /www/nginx/conf/cert/docker.djc8.cn
  • 创建nginx.conf
    进入/www/nginx/conf目录,创建文件touch /www/nginx/conf/nginx.conf,并且输入以下内容:
user nginx;
worker_processes  3;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
worker_rlimit_nofile 5120;
events {
    use epoll;
    worker_connections  5120;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 8 64k;
    client_max_body_size 100m;
    limit_conn_zone $binary_remote_addr zone=one:32k;

    sendfile        on;
    tcp_nopush     on;

    keepalive_timeout  60;
    tcp_nodelay on;

    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types       text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for';
    #include default.conf;
    include vhost/*.conf;
}

cd 进入到/www/nginx/conf/vhost目录,创建文件docker.djc8.cn.conf这个文件最好用域名作为名称,方便后续维护。
修改docker.djc8.cn.conf

server {
        listen       80;
        root /www;
        server_name docker.djc8.cn;
        index  index.html index.php index.htm;
        rewrite ^(.*)$  https://$host$1 permanent;
        error_page  400 /errpage/400.html;
        error_page  403 /errpage/403.html;
        error_page  404 /errpage/404.html;
        error_page  500 /errpage/500.html;
        error_page  503 /errpage/503.html;
        location ~ \.php(.*)$ {
                fastcgi_pass  djc8php:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /var/www/html$fastcgi_script_name;
                fastcgi_param PATH_INFO $2;
                include fastcgi_params;
        }
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
                expires      1d;
        }
        location ~ .*\.(js|css|html|htm)?$ {
                expires      12h;
        }
        location ~ /\.ht {
                deny  all;
        }
        location / {
                 try_files $uri $uri/ /?$args;
        }
   
}
server {
        listen       443;
        root /www;
        ssl                  on;
        ssl_certificate      cert/docker.djc8.cn/1_docker.djc8.cn_bundle.crt;
        ssl_certificate_key  cert/docker.djc8.cn/2_docker.djc8.cn.key;
        ssl_prefer_server_ciphers on;
        ssl_session_timeout 10m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_ciphers EECDH+CHACHA20:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5;
        server_name docker.djc8.cn;
        index  index.html index.php index.htm;
        error_page  400 /errpage/400.html;
        error_page  403 /errpage/403.html;
        error_page  404 /errpage/404.html;
        error_page  500 /errpage/500.html;
        error_page  503 /errpage/503.html;
        location ~ \.php(.*)$ {
                fastcgi_pass  djc8php:9000;
                fastcgi_index  index.php;
                fastcgi_param  SCRIPT_FILENAME  /var/www/html$fastcgi_script_name;
                fastcgi_param PATH_INFO $2;
                include fastcgi_params;
        }
        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
                expires      1d;
        }
        location ~ .*\.(js|css|html|htm)?$ {
                expires      12h;
        }
        location ~ /\.ht {
	            deny  all;
	    }
        location / {
                 try_files $uri $uri/ /?$args;
        }
        location ~ /.well-known {
                 allow all;
        }
}

我这里因为有https的访问,所以加了两个端口80443,访问80端口,会自动跳转到443端口,实现全站https访问。其中的cert目录是用来存放证书的,如果要免费的证书,可以参考我的这篇文章nginx利用certbot4docker 自动续期证书
尤其注意fastcgi_pass这里的djc8php就是我前面增加的php容器的名称,因为我的网络配置了一样的,所以直接使用docker别名就可以直接访问了。

  • 启动nginx镜像容器
[root@VM-0-11-centos vhost]# docker run -d -p 80:80 -p 443:443 --name djc8nginx \
>  --network=djc8net \
>  -v /www/nginx/logs:/var/log/nginx/ \
>  -v /www/nginx/conf/nginx.conf:/etc/nginx/nginx.conf  \
>  -v /www/nginx/conf/vhost:/etc/nginx/vhost \
>  -v /www/nginx/conf/cert/:/etc/nginx/cert/ \
>  -v /www/web/public_html:/www \
>  nginx:1.18.0

ff0ad0c0ee584205cd04c3a71d19cd2b276d63b988ac3ee661f2bb77f706dec4

  • 创建index.php文件
touch /www/web/public_html/index.php
  • 编辑index.php,并输入如下内容
<?
phpinfo();
  • 浏览器输入:https://docker.djc8.cn/index.php

2020-12-31_11-39.png

mysql

mysql安装

[root@VM-0-11-centos /]# docker pull mysql:8.0.22
8.0.22: Pulling from library/mysql
6ec7b7d162b2: Already exists 
fedd960d3481: Pull complete 
7ab947313861: Pull complete 
64f92f19e638: Pull complete 
3e80b17bff96: Pull complete 
014e976799f9: Pull complete 
59ae84fee1b3: Pull complete 
ffe10de703ea: Pull complete 
657af6d90c83: Pull complete 
98bfb480322c:
 Pull complete 
6aa3859c4789: Pull complete 
1ed875d851ef: Pull complete 
Digest: sha256:78800e6d3f1b230e35275145e657b82c3fb02a27b2d8e76aac2f5e90c1c30873
Status: Downloaded newer image for mysql:8.0.22
docker.io/library/mysql:8.0.22

mysql配置

先运行下面的shell命令

[root@VM-0-11-centos /]# sudo docker run --rm -p 9306:3306 --network=djc8net --name djc8mysql -v /www/mysql/date:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=djc8learndocker -d mysql:8.0.22
35a2fd7ddea9e02f3c5c52d27d28344f2dbed4a69d84fe3daadae253bf3f6e71

我这里开了9306的端口,其实最好不要开(直接去掉-p 9306:3306),并且映射卷目录到/www/mysql/date,这样在下次重启mysql的时候,依然能够使用对应的数据库文件。
并且设置了一个mysql的root用户的密码为djc8learndocker
现在让我们看下,都开启了哪些容器,这些容器的状态,端口是咋样的,执行命令:

[root@VM-0-11-centos /]# docker ps -a
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS          PORTS                                      NAMES
35a2fd7ddea9   mysql:8.0.22    "docker-entrypoint.s…"   52 seconds ago   Up 50 seconds   33060/tcp, 0.0.0.0:9306->3306/tcp          djc8mysql
ff0ad0c0ee58   nginx:1.18.0    "/docker-entrypoint.…"   2 hours ago      Up 2 hours      0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp   djc8nginx
33716536dc13   djc8/php:8fpm   "docker-php-entrypoi…"   3 hours ago      Up 3 hours      0.0.0.0:9000->9000/tcp                     djc8php

可以看到,3个容器都正常的启动着。端口映射也没问题。

创建数据库并且导入

数据准备

准备一个要导入的sql文件,文件名import.sql,放到/www/mysql/sql/,我这里准备了一条建表语句,如下

create table `djc8learndocker`(
`author` varchar(200) DEFAULT NULL,
`mail` varchar(200) DEFAULT NULL
);
insert into djc8learndocker (`author`,`mail`) values ('djc8','admin@djc8.cn');

现在将这个sql导入到mysql的容器中,也就是djc8mysql容器,执行如下脚本

[root@VM-0-11-centos sql]#  docker cp /www/mysql/sql/import.sql djc8mysql:/tmp/import.sql

现在进入到djc8mysql 容器中
执行如下命令进入到容器中

这个命令很常用,其中-i代表接受标准输入命令,后面的t则代表开启伪终端

[root@VM-0-11-centos sql]# docker exec -it djc8mysql /bin/bash
root@35a2fd7ddea9:/# 

看到root@35a2fd7ddea9:/#就代表进来了,可能你会发现35a2fd7ddea9很眼熟,没错,这个就是docker帮我们生成的一个id,你在用docker ps -a 命令的时候,第一列就是这个啦!,那么这个可以更改吗?(我不知道,有大佬可以告诉我吗?)

接下来看下上一步导入的sql文件,执行:

root@35a2fd7ddea9:/# ls /tmp/
import.sql

可以看到import.sql已经在容器中的了。

导入数据

执行命令


root@35a2fd7ddea9:/# mysql -u root -pdjc8learndocker
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

之后执行创建数据库语句,并且使用该数据库

mysql> create database djc8db;
Query OK, 1 row affected (0.03 sec)
mysql> use djc8db;
Database changed
mysql> 

执行导入sql语句

mysql> source /tmp/import.sql
Query OK, 0 rows affected (0.04 sec)

Query OK, 1 row affected (0.01 sec)

重新查询看下:

mysql> select * from djc8learndocker;
+--------+-----------------------+
| author | mail                  |
+--------+-----------------------+
| djc8   | chensongguo#gmail.com |
+--------+-----------------------+
1 row in set (0.00 sec)

mysql>

现在,执行:exit从mysql命令行中退出,在mysql容器中,再次执行exit退出容器命令行,回到宿主机。

mysql> exit;
Bye
root@35a2fd7ddea9:/# exit;
exit
[root@VM-0-11-centos sql]# 

连接php并查询出数据

进入目录/www/web/public_html/,修改index.php文件为如下内容

<?
    $mysqli = new mysqli("djc8mysql", "root", "djc8learndocker", "djc8db");
    $sql = "SELECT * FROM djc8learndocker";
    $result = $mysqli->query($sql);
    $row = $result->fetch_assoc();
    echo 'this page by '.$row["author"].' | '.$row["mail"];
    $result->free();  
    $mysqli->close(); 

现在访问:https://docker.djc8.cn
2020-12-31_14-27.png

Redis

安装redis

redis是非关系型数据库,又是内存数据库,支持key-value形式的方式存储数据,速度快,分布式,使用简单,能显著的提高网站的并发量,值得一用。
使用下面的脚本,开启redis数据库

[root@VM-0-11-centos sql]# docker run -p 9379:6379  -d --network=djc8net --name djc8redis  redis:6.0.9
Unable to find image 'redis:6.0.9' locally
6.0.9: Pulling from library/redis
6ec7b7d162b2: Already exists 
1f81a70aa4c8: Pull complete 
968aa38ff012: Pull complete 
884c313d5b0b: Pull complete 
6e858785fea5: Pull complete 
78bcc34f027b: Pull complete 
Digest: sha256:0f724af268d0d3f5fb1d6b33fc22127ba5cbca2d58523b286ed3122db0dc5381
Status: Downloaded newer image for redis:6.0.9
9b4a71b107073a21b382d329779688a695a8b316c2fb94484b47bd65f3aad99b

简单,方便,接下来在php中用一下。
进入目录/www/web/public_html/,修改index.php文件为如下内容

<?
    $mysqli = new mysqli("djc8mysql", "root", "djc8learndocker", "djc8db");
    $sql = "SELECT * FROM djc8learndocker";
    $result = $mysqli->query($sql);
    $row = $result->fetch_assoc();

    $redis = new Redis();  
    $redis->connect('djc8redis', 6379);
    //$redis->auth('mypassword');
    if(!$redis->exists("index.php")){
        $redis ->set( "index.php" , 'this page by '.$row["author"].' | '.$row["mail"].' use redis');   
    }
    echo $redis ->get( "index.php");
     $result->free();  
     $mysqli->close(); 

现在访问:https://docker.djc8.cn
2020-12-31_14-42.png
现在可以进入到djc8redis容器中,使用redis-cli工具查看下了。
执行:

[root@VM-0-11-centos sql]# docker exec -it djc8redis /bin/bash
root@9b4a71b10707:/data# redis-cli
127.0.0.1:6379> keys *
1) "index.php"
127.0.0.1:6379> 

可以看到keys *命令已经能查到key,那么看下value

127.0.0.1:6379> get index.php
"this page by djc8 | admin@djc8.cn use redis"

成功了!

本文来自:[Docker]完整上线一个php+nginx+mysql+redis架构的网站-小码农,转载请保留本条链接,感谢!

温馨提示:
本文最后更新于 2024年07月27日,已超过 116 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
正文到此结束
该篇文章的评论功能已被站长关闭
本文目录