实践项目-基于K8s平台进行wordpress建站

(已更新完)

基本信息

系统:Debian 12.05
k8s版本:1.2x
环境:虚拟机

序号 IP地址 域名 主机名
1 192.168.100.12 k8s-master.yourname.com k8s-master
2 192.168.100.15 k8s-node1.yourname.com k8s-node1
3 192.168.100.16 k8s-node2.yourname.com k8s-node2
4 192.168.100.21 k8s-register.yourname.com k8s-register

基本设置

VMware虚拟网络编辑器

image
image

ssh设置

sudo apt-get update && apt-get upgrade
sudo apt-get install vim

/etc/ssh/sshd_config

...
PermitRootLogin yes
PubkeyAuthentication no
...

master连通其他node

 for i in master node1 node2 register; do ssh-copy-id root@k8s-$i; done

镜像修改国内源

阿里云Debian系统镜像

sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list

静态IP设置

/etc/network/interfaces
其他主机修改IP即可

# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

auto ens33
iface ens33 inet static
address 192.168.100.12
netmask 255.255.255.0
gateway 192.168.100.254
search localdomain
nameserver 8.8.8.8
nameserver 114.114.114.114
/etc/init.d/networking restart

主机名和域名

/etc/hostname

k8s-master

/etc/hosts

127.0.0.1       localhost
127.0.1.1       k8s01

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

192.168.100.12 k8s-master.yourname.com k8s-master
192.168.100.15 k8s-node1.yourname.com k8s-node1
192.168.100.16 k8s-node2.yourname.com k8s-node2
192.168.100.21 k8s-register.yourname.com k8s-register

用scp将hosts文件传输到node

for i in node1 node2 register; do scp /etc/hosts root@k8s-$i:/etc/hosts; done

关闭swap

# 关闭当前已启用的swap分区
swapoff -a

#禁用swap设备
sed -i 's/.*swap.*/#&/' /etc/fstab

#内核禁用swap参数
cat >> /etc/sysctl.d/k8s.conf << EOF
vm.swappiness=0
EOF

内核优化

#配置iptables参数,允许流量通过防火墙
cat << EOF | sudo tee /etc/sysctl.d/k8s.conf
net.ipv4.ip_forward = 1
EOF
#下载overlay和br_netfilter
sudo modprobe overlay
sudo modprobe br_netfilter

lsmod | grep overlay
lsmod | grrp br_netfilter
#加载k8s.conf
sysctl -p /etc/sysctl.d/k8s.conf

kubeadm安装

安装 kubeadm | Kubernetes文档

更新 apt 包索引并安装使用 Kubernetes apt 仓库所需要的包

sudo apt-get update
# apt-transport-https 可能是一个虚拟包(dummy package);如果是的话,你可以跳过安装这个包
sudo apt-get install -y apt-transport-https ca-certificates curl gpg

下载用于 Kubernetes 软件包仓库的公共签名密钥(阿里云国内源)

# 如果 `/etc/apt/keyrings` 目录不存在,则应在 curl 命令之前创建它,请阅读下面的注释。
# sudo mkdir -p -m 755 /etc/apt/keyrings

curl -fsSL https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.30/deb/Release.key |     gpg --dearmor -o /etc/apt/keyrings/kubernetes-apt-keyring.gpg

添加 Kubernetes apt 仓库(阿里云国内源)

echo "deb [signed-by=/etc/apt/keyrings/kubernetes-apt-keyring.gpg] https://mirrors.aliyun.com/kubernetes-new/core/stable/v1.30/deb/ /" | tee /etc/apt/sources.list.d/kubernetes.list

更新 apt 包索引,安装 kubelet、kubeadm 和 kubectl,并锁定其版本

sudo apt-get update
sudo apt-get install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl

Docker Engine安装

Debian系统安装Docker Engine | Docker文档

删除旧版本Docker

for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do sudo apt-get remove $pkg; done

添加密钥和存储库

# 添加Docker的官方GPG密钥:
sudo apt-get update
sudo apt-get install ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc

# 将存储库添加到Apt源:
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian \
  $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update

安装Docker组件

sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

#检验时候安装成功
sudo docker run hello-world

容器环境修改

mkdir -p /home/data/{softs,server,tools}
systemctl stop docker
cat >> /etc/docker/daemon.json << EOF
{
 "registry-mirrors":[
   "http://hub-mirror.c.163.com",
   "https://mirror.baidubce.com",
   "https://docker.mirrors.sjtug.sjtu.edu.cn"
 ],
 "insecure-registries":["k8s-register.yourname.com"],
 "exec-opts":["native.cgroupdriver=systemd"],
 "runtimes": {
    "custom": {
      "path": "/usr/local/bin/my-runc-replacement",
      "runtimeArgs": [
        "--debug"
      ]
    }
  }
}
EOF
systemctl daemon-reload
systemctl start docker

Harbor仓库搭建

Harbor主页

#k8s-register执行,关闭Debian系统里的apache
systemctl stop apache2
cd /home/data/softs

wget https://github.com/goharbor/harbor/releases/download/v2.11.0-rc1/harbor-offline-installer-v2.11.0-rc1.tgz

tar -zxvf harbor-offline-installer-v2.11.0-rc1.tgz -C /home/data/server
cd /home/data/server/harbor

docker load < harbor.v2.11.0.tar.gz
docker images

cp harbor.yml.tmpl{,.bak}

images镜像

REPOSITORY                      TAG       IMAGE ID       CREATED         SIZE
goharbor/harbor-exporter        v2.11.0   553bf54feb6a   3 days ago      108MB
goharbor/redis-photon           v2.11.0   f8d119d79368   3 days ago      165MB
goharbor/trivy-adapter-photon   v2.11.0   7d0463fdcf2a   3 days ago      498MB
goharbor/harbor-registryctl     v2.11.0   ec03a8c8a09e   3 days ago      162MB
goharbor/registry-photon        v2.11.0   2d8ee161f0e4   3 days ago      84.5MB
goharbor/nginx-photon           v2.11.0   1e2296f9e618   3 days ago      153MB
goharbor/harbor-log             v2.11.0   376053bebc25   3 days ago      163MB
goharbor/harbor-jobservice      v2.11.0   b64aa39a5179   3 days ago      158MB
goharbor/harbor-core            v2.11.0   36c4bd04c98e   3 days ago      185MB
goharbor/harbor-portal          v2.11.0   c076e09f295d   3 days ago      162MB
goharbor/harbor-db              v2.11.0   d10461eddcd1   3 days ago      271MB
goharbor/prepare                v2.11.0   9fb0b7c71e35   3 days ago      207MB
hello-world                     latest    d2c94e258dcb   12 months ago   13.3kB

配置harbor.yml.tmpl

hostname: k8s-register.yourname.com

http:
  port: 80

harbor_admin_password: 123456

data_volume: /data/server/harbor/data

运行harbor

mv harbor.yml.tmpl harbor.yml

./prepare
./install.sh


docker-compose ps

      Name                   Command                    State                     Ports
-------------------------------------------------------------------------------------------------
harbor-core         /harbor/entrypoint.sh       Up (health: starting)
harbor-db           /docker-entrypoint.sh 14    Exit 128
                    15
harbor-jobservice   /harbor/entrypoint.sh       Restarting
harbor-log          /bin/sh -c                  Up (health: starting)   127.0.0.1:1514->10514/tcp
                    /usr/local/bin/ ...
harbor-portal       nginx -g daemon off;        Exit 128
nginx               nginx -g daemon off;        Exit 128
redis               redis-server                Exit 128
                    /etc/redis.conf
registry            /home/harbor/entrypoint.s   Exit 2
                    h
registryctl         /home/harbor/start.sh       Exit 1

启动后游览器登陆IP:80,则出现Harbor管理页面
输入admin账号和密码
image

定制启动服务文件

# vim /lib/systemd/system/harbor.service
[Unit]
Description=Harbor
After=docker.service systemd-networkd.service systemd-resolved.service
Requires=docker.service
Documentation=https://github.com/goharbor/harbor

[Service]
Type=simple
Restart=on-failure
RestartSec=5
ExecStart=/usr/bin/docker-compose --file /home/data/server/harbor/docker-compose.yml up
ExecStop=/usr/bin/docker-compose --file /home/data/server/harbor/docker-compose.yml down

[Install]
WantedBy=multi-user.target

创建项目

创建用户
image
创建后退出admin登陆新用户

image
访问级别选择公开

# k8s-master执行

docker pull nginx
docker pull busybox

# 确保"insecure-registries"里是你的域名
cat /etc/docker/daemon.json

#登陆新用户,给busybox打上标签,拉取busybox
docker login k8s-register.yourname.com -u yourname
docker tag busybox k8s-register.yourname.com/wordpress/busybox
docker push k8s-register.yourname.com/wordpress/busybox

cri-dockerd部署

cri-dockerd | github

cd /home/data/softs
wget https://github.com/Mirantis/cri-dockerd/releases/download/v0.3.14/cri-dockerd-0.3.14.amd64.tgz

tar -zxvf cri-dockerd-0.3.14.amd64.tgz
mv cri-dockerd/cri-dockerd /usr/local/bin/

cri-dockerd --version
# cri-dockerd 0.3.14 (683f70f)

whereis cri-dockerd
# cri-dockerd: /usr/local/bin/cri-dockerd

定制cri-dockerd启动服务文件

# vim /etc/systemd/system/cri-docker.service
[Unit]
Description=CRI Interface fo Docker Application Container Engine
After=network-online.target firewalld.service docker.service
Wants=network-online.target
Documentation=https://docs.mirantis.com/

[Service]
Type=notify
ExecStart=/usr/local/bin/cri-dockerd --network-plugin=cni --cni-conf-dir=/etc/cni/net.d --cni-bin-dir=/opt/cni/bin --container-runtime-endpoint=unix:///var/run/cri-dockerd.sock --cri-dockerd-root-directory=/var/lib/dockershim --docker-endpoint=unix:///var/run/docker.sock --cri-dockerd-root-directory=/var/lib/docker --pod-infra-container-image=k8s-register.yourname.com/google_containers/pause:3.9
ExecReload=/bin/kill -s HUP $MAINPID
TimeoutSec=0
RestartSec=2
Restart=always
StartLimitBurst=3
StartLimitInterval=60s
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
Delegate=yese
KillMode=process

[Install]
WantedBy=multi-user.target

定制cri-dockerd.sock启动服务文件

[Unit]
Description=CRI Docker Socket for the API
PartOf=cri-docker.service

[Socket]
ListenStream=/var/run/cri-dockerd.sock
SocketMode=0660
SocketUser=root
SocketGroup=docker

[Install]
WantedBy=sockets.target

启动运行

systemctl daemon-reload
systemctl enable cri-docker
systemctl start cri-docker
systemctl status cri-docker

传输启动服务文件到node1和node2

for i in node1 node2; do scp /usr/local/bin/cri-dockerd root@k8s-$i:/usr/local/bin/cri-dockerd; scp /usr/lib/systemd/system/cri-docker.socket root@k8s-$i:/usr/lib/systemd/system/cri-docker.socket; scp /etc/systemd/system/cri-docker.service root@k8s-$i:/etc/systemd/system/cri-docker.service; done

# node1和node2检测是否收到
systemctl daemon-reload
systemctl enable cri-docker
systemctl start cri-docker
systemctl status cri-docker

k8s集群部署

kubeadm version
kubeadm config images list
#阿里云google_containers
docker pull registry.aliyuncs.com/google_containers/kube-apiserver:v1.29.0

for i in $(kubeadm config images list --kubernetes-version=1.29.0 | awk -F '/' '{print $NF}'); do docker pull registry.aliyuncs.com/google_containers/$i; docker tag registry.aliyuncs.com/google_containers/$i k8s-register.yourname.com/google_containers/$i; docker push k8s-register.yourname.com/google_containers/$i; docker rmi registry.aliyuncs.com/google_containers/$i; done

kubeadm init --kubernetes-version=1.30.1 --service-cidr="10.96.0.0/12" --pod-network-cidr="10.244.0.0/16" --apiserver-advertise-address="192.168.100.12" --ignore-preflight-errors=Swap --image-repository=k8s-register.yourname.com/google_containers --cri-socket=unix:///var/run/cri-dockerd.sock

mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config

mkdir /home/data/kubernetes/network/flannel -p
cd/home/data/kubernetes/network/flannel
cd /home/data/kubernetes/network/flannel
wget https://github.com/flannel-io/flannel/releases/latest/download/kube-flannel.yml
cp kube-flannel.yml{,.bak}
grep image kube-flannel.yml | sort | uniq | awk -F '/' '{print $NF}'

for i in $(grep image kube-flannel.yml | sort | uniq | awk -F '/' '{print $NF}'); do docker pull docker.io/flannel/$i; docker tag docker.io/flannel/$i k8s-register.yourname.com/google_containers/$i; docker push k8s-register.yourname.com/google_containers/$i; docker rmi docker.io/flannel/$i; done

sed -i 's#docker.io/flannel#k8s-register.yourname.com/google_containers#g' kube-flannel.yml

kubectl apply -f kube-flannel.yml

kubectl get node

补全命令配置

vim /root/.bashrc
···
source <(kubectl completion bash)
source <(kubeadm completion bash)
···

构建镜像并在k8s部署

  • 添加lnmp的容器网段
  • Wordpress安装在宿主机
  • php、Mysql、Nginx装在容器内
  • 安装ingress
    • 创建HTTP证书
  • k8s部署wordpress
    • 指定mysql的Namespace
    • 指定mysql服务于端口号
    • 配置mysql的Pod信息与镜像来源
    • 指定wordpress的Namespace
    • 指定wordpress的协议端口与代理端口
    • 配置wordpress的Pod信息与镜像来源
    • 部署证书
  • 镜像推送Harbor

Docker网段

docker network create lnmp
docker network ls
#找到NAME为lnmp的网卡id
ifconfig
#找到网卡ID相同的IP地址
172.19.0.1

Wordpress部分

cd /home/data/server
wget https://cn.wordpress.org/wordpress-6.5.3-zh_CN.tar.gz
tar -xf wordpress-6.5.3-zh_CN.tar.gz

/nginx/wordpress/wp-config.php
/php/wordpress/wp-config.php

/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );

/** MySQL database username */
define( 'DB_USER', 'wp' );

/** MySQL database password */
define( 'DB_PASSWORD', 'yourpasswd' );

/** MySQL hostname */
define( 'DB_HOST', 'mysql.mysql.svc.cluster.local' );


* @link https://wordpress.org/support/article/debugging-in-wordpress/
define( 'WP_DEBUG', true );

php部分

Dockerfile

# apt-cache depends php 通过apt-cahce查出php需要什么依赖包

# phpinfo给出加装什么支持的模块

--prefix # 指定安装目录
--with-config-file-scan-dir # 指定php配置文件目录

# 支持mysql的模块
--with-pdo-mysql
--with-mysqli

# 加密扩展的模块
--with-mhash
--with-openssl

# 国际化与字符编码支持
--with-iconv
--with-gettext

# 压缩与归档扩展
--with-zlib

# URL交互
--with-curl
--enable-xml
--with-xmlrpc
--enable-sockets
--enable-ftp

# 不包含PEAR库
--without-pear

# 不包含GDBM库
--without-gdbm

# 禁用调试模式
--disable-debug

# 禁用运行时路径
--disable-rpath

# 禁用文件类型检测
--disable-fileinfo

# 启用内联优化
--enable-inline-optimization

# 启用共享库的支持
--enable-shared

# 启用bcmath扩展
--enable-bcmath

# 允许PHP访问共享内存段,访问System V信号量和共享内存
--enable-shmop
--enable-sysvsem
--enable-sysvshm

# 启用多字节正则表达式支持
--enable-mbregex

# 启用进程控制功能
--enable-pcntl

# 启用SOAP协议
--enable-soap

# 启用会话支持
--enable-session

# 启用OPcache扩展,用于加速PHP脚本的执行
--enable-opcache

# 启用PHP-FPM
--enable-fpm

# 快速安装
--enable-fast-install
FROM debian
USER root
RUN sed -i 's/deb.debian.org/mirrors.huaweicloud.com/g' /etc/apt/sources.list.d/debian.sources
RUN apt-get install apt-transport-https
RUN apt-get update && apt-get upgrade
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
RUN echo 'Asia/Shanghai' >/etc/timezone
ENV PATH /usr/local/php/bin:/usr/local/php/sbin:$PATH
RUN apt-get update && apt-get install -y gcc \
g++ \
make \
libxml2 \
openssl \
libcurl4-openssl-dev \
libfreetype-dev \
slapd \
libsqlite3-dev \
libzip-dev \
libxml2-dev \
libssl-dev \
pkg-config


ADD php-8.3.7.tar.gz /usr/local/src
WORKDIR /usr/local/src/php-8.3.7
RUN ./configure \
    --prefix=/usr/local/php \
    --with-config-file-scan-dir=/usr/local/php/etc/ \
    --with-mhash --with-pdo-mysql \
    --with-openssl --with-mysqli \
    --with-iconv --with-zlib \
    --disable-debug --disable-rpath \
    --enable-shared --enable-xml \
    --enable-bcmath --enable-shmop \
    --enable-sysvsem --enable-sysvshm --enable-mbregex \
    --enable-ftp \
    --enable-pcntl --enable-sockets \
    --enable-soap \
    --without-pear --with-gettext \
    --enable-session --with-curl \
    --enable-opcache --enable-fpm \
    --without-gdbm --enable-fast-install \
    --disable-fileinfo

RUN make && make install
RUN groupadd www -g 666 && \
    useradd www -u 666 -g www -s /sbin/nologin -M
ADD www.conf /usr/local/php/etc/php-fpm.d/
ADD php.ini /usr/local/php/etc/
ADD php-fpm.conf /usr/local/php/etc/
EXPOSE 9000
CMD ["/usr/local/php/sbin/php-fpm","-F"]

php.ini

php.ini-production | github php.ini文件选项详解

[PHP]
short_open_tag = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
serialize_precision = -1
zend.enable_gc = On
zend.exception_ignore_args = On
expose_php = On
max_execution_time = 30
max_input_time = 60
memory_limit = 128M
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off
display_startup_errors = Off
log_errors = On
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
xmlrpc_errors = 0
xmlrpc_error_number = 0
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 200M
default_mimetype = "text/html"
default_charset = "UTF-8"
enable_dl = Off
file_uploads = On
upload_max_filesize = 200M
max_file_uploads = 20
allow_url_fopen = On
allow_url_include = Off
default_socket_timeout = 60
extension=curl
extension=ftp
extension=gettext
extension=mysqli
extension=odbc
extension=openssl
extension=pdo_mysql
extension=pdo_odbc
extension=shmop
extension=soap
extension=sockets
zend_extension=opcache
[CLI Server]
cli_server.color = On
[iconv]
[Pdo]
pdo_odbc.connection_pooling=strict
[Pdo_mysql]
pdo_mysql.default_socket=
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = Off
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[bcmath]
bcmath.scale = 0
[Session]
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.cookie_samesite =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.sid_length = 26
session.trans_sid_tags = "a=href,area=href,frame=src,form="
session.sid_bits_per_character = 5
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[ffi]
ffi.enable=true

www.conf

[www]
user = www
group = www
listen = 9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
request_terminate_timeout = 1

php-fpm.conf

[global]
daemonize = no
include=/usr/local/php/etc/php-fpm.d/*.conf

Nginx部分

Dockerfile

FROM nginx
RUN groupadd www -g 666 && \
    useradd www -u 666 -g 666 -s /sbin/nologin -M
ADD yourname.wp.com.conf /etc/nginx/conf.d/
ADD nginx.conf /etc/nginx/
RUN mkdir /server/wordpress/ -p
RUN rm -rf /etc/nginx/conf.d/default.conf
EXPOSE 80
WORKDIR /root
CMD ["nginx","-g","daemon off;"]

Nginx.conf

user  www;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
    worker_connections  1024;
}
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    include /etc/nginx/conf.d/*.conf;
}

yourname.wp.com.conf

server {
    listen 80;
    server_name yourname.wp.com;
    charset utf-8
    location / {
        root /server/wordpress;
        index index.html index.php;
    }
    
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /server/wordpress;
    }

    location ~* \.php$ {
        root /server/wordpress;
        fastcgi_pass php:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /server/wordpress/$fastcgi_script_name;
        include fastcgi_params;
    }
}

Mysql部分

Dockerfile

FROM mysql:8.4.0

ENV MYSQL_ALLOW_EMPTY_PASSWORD yes

ADD setup.sh /mysql/setup.sh
ADD schema.sql /mysql/schema.sql
ADD privileges.sql /mysql/privileges.sql


CMD ["sh", "/mysql/setup.sh"]

privileges.sql

use mysql;
grant all on wordpress.* to wp@'10.244.%.%' identified by 'yourpasswd';
grant all on wordpress.* to wp@'172.19.0.%' identified by 'yourpasswd';
SET PASSWORD=PASSWORD('yourpasswd');
flush privileges;

schema.sql

CREATE DATABASE wordpress;

setup.sh

set -e

echo `systemctl status mysql`
 
echo '1.Start mysql'
systemctl start mysql
sleep 3
echo `systemctl status mysql`
 
echo '2.Import data'

mysql < /mysql/schema.sql
echo '3.Import completed'
 
sleep 3
echo `systemctl status mysql`
 

echo '4.Change password'
mysql < /mysql/privileges.sql
echo '5.Change password completed'
 

echo `systemctl status mysql`
echo `Complete the all`
 
tail -f /dev/null

构建镜像

在k8s-register账号进行

cd /home/data/server/php
docker build -t lnmp-php-wp:v1 .

cd /home/data/server/mysql
docker build -t lnmp-mysql-wp:v1 .

cd /home/data/server/nginx
docker build -t lnmp-nginx-wp:v1 .

docker login docker login k8s-register.yourname.com -u yourname

docker tag lnmp-nginx-wp:v1 k8s-register.yourname.com/wordpress/lnmp-nginx-wp:v1
docker tag lnmp-mysql-wp:v1 k8s-register.yourname.com/wordpress/lnmp-mysql-wp:v1
docker tag lnmp-php-wp:v1 k8s-register.yourname.com/wordpress/lnmp-php-wp:v1

docker push k8s-register.yourname.com/wordpress/lnmp-mysql-wp:v1
docker push k8s-register.yourname.com/wordpress/lnmp-nginx-wp:v1
docker push k8s-register.yourname.com/wordpress/lnmp-php-wp:v1

k8s配置Ingress

wget https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.10.1/deploy/static/provider/cloud/deploy.yaml

sed -i 's#registry.k8s.io/ingress-nginx/controller:v1.10.1@sha256:e24f39d3eed6bcc239a56f20098878845f62baa34b9f2be2fd2c38ce9fb0f29e#registry.cn-hangzhou.aliyuncs.com/k8sos/ingress-controller:v1.10.1#g' deploy.yaml

kubectl apply -f deploy.yaml

kubectl get pods -n ingress-nginx
openssl genrsa -out tls.key 2048
openssl req -new -x509 -key tls.key -out tls.crt -subj /C=CN/ST=ShangHai/L=ShangHai/O=Ingress/CN=yourname.wp.local

搭建wordpress

cat > configlist.yaml <<EOF
apiVersion: v1
kind: Namespace
metadata:
  name: mysql
---
kind: Service
apiVersion: v1
metadata:
  name: mysql
  namespace: mysql
spec:
  ports:
    - name: http
      port: 3306
      targetPort: 3306
  selector:
    app: mysql
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: name-mysql
  namespace: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
        - name: mysql
          image: k8s-register.yourname.com/lnmp-mysql-wp:v1
---
apiVersion: v1
kind: Namespace
metadata:
  name: wordpress
---
apiVersion: v1
kind: Service
metadata:
  name: wordpress
  namespace: wordpress
spec:
  type: NodePort
  ports:
    - name: http
      port: 80
      targetPort: 80
      protocol: TCP
      nodePort: 30080
    - name: https
      port: 443
      targetPort: 443
      protocol: TCP
  selector:
    app: wordpress
---
kind: Deployment
apiVersion: apps/v1
metadata:
  name: wordpress
  namespace: wordpress
spec:
  selector:
    matchLabels:
      app: wordpress
  template:
    metadata:
      labels:
        app: wordpress
    spec:
      containers:
        - name: php
          image: k8s-register.yourname.com/lnmp-php-wp:v1
        - name: nginx
          image: k8s-register.yourname.com/lnmp-nginx-wp:v1
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: wordpress
  namespace: wordpress
spec:
  tls:
    - secretName: ingress-tls
  rules:
    - host: yourname.wp.local
      http:
        paths:
          - path: /
            backend:
              serviceName: wordpress
              servicePort: 80
EOF
kubectl -n wordpress create secret tls ingress-tls --cert=tls.crt --key=tls.key

kubectl apply -f configlist/configlist.yaml

kubectl get pod -n mysql
kubectl get pod -n wordpress


windows hosts:
192.168.100.12 yourname.wp.local
192.168.100.12:30080
http://yourname.wp.local:30080


https://yourname.wp.local:32719/wp-admin/install.php

posted @ 2024-05-31 11:52  Mugetsukun  阅读(162)  评论(0编辑  收藏  举报