【k8s】Wordpress(PHP+nginx+mysql)迁移到k8s

一、迁移思路:

1、制作服务镜像;
1.1 挑选合适的基础镜像;
1.2 准备代码相关的文件;
1.3 通过dockerfile构建镜像;

2、制作Kubernetes服务,并完成调度;
2.1确定服务运行的模式(内部运行or 对外提供);
2.2确定服务所使用的控制器;
2.3服务是否需要后端存储pvc;
2.4服务是否需要配置管理configmap;
2.5服务是否需要Service、Ingress等;

在这里插入图片描述

在这里插入图片描述

二、前期准备

1、下载wordpress源码

wget https://cn.wordpress.org/wordpress-6.0-zh_CN.tar.gz
tar xf wordpress-6.0-zh_CN.tar.gz
cd wordpress/

[root@node4 wordpress]# ls
index.php    readme.html      wp-admin            wp-comments-post.php  wp-content   wp-includes        wp-load.php   wp-mail.php      wp-signup.php     xmlrpc.php
license.txt  wp-activate.php  wp-blog-header.php  wp-config-sample.php  wp-cron.php  wp-links-opml.php  wp-login.php  wp-settings.php  wp-trackback.php

2、准备wp-config. php文件,需要修改里面的数据连接信息(使用变量,后期进行替换)、以及Authentication的key

wp-config. php

<?php
/**
 * The base configuration for WordPress
 *
 * The wp-config.php creation script uses this file during the installation.
 * You don't have to use the web site, you can copy this file to "wp-config.php"
 * and fill in the values.
 *
 * This file contains the following configurations:
 *
 * * Database settings
 * * Secret keys
 * * Database table prefix
 * * ABSPATH
 *
 * @link https://wordpress.org/support/article/editing-wp-config-php/
 *
 * @package WordPress
 */

// ** Database settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define( 'DB_NAME', '{DB_NAME}' );

/** Database username */
define( 'DB_USER', '{DB_USER}' );

/** Database password */
define( 'DB_PASSWORD', '{DB_PASSWORD}' );

/** Database hostname */
define( 'DB_HOST', '{DB_HOST}' );

/** Database charset to use in creating database tables. */
define( 'DB_CHARSET', 'utf8' );

/** The database collate type. Don't change this if in doubt. */
define( 'DB_COLLATE', '' );

/**#@+
 * Authentication unique keys and salts.
 *
 * Change these to different unique phrases! You can generate these using
 * the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}.
 *
 * You can change these at any point in time to invalidate all existing cookies.
 * This will force all users to have to log in again.
 *
 * @since 2.6.0
 */
define('AUTH_KEY',         '_78BG!]+f4gO,]UDYt[.<_Fk,sf|V|;<9p5%wyDsEx!;*:=]#FahHwhPnA8Q`7Bf');
define('SECURE_AUTH_KEY',  'R<Cdu]uti=U~PJnvG7n$+~X_At1CL=x8XPICi,lZ3p6nJFYPn~`M|]tpk0~[q~i>');
define('LOGGED_IN_KEY',    'g,j8IK1a,+uNlaB1D=*y-WF``N|Q$kD 4+~#PPE!pnQ2L8&M=1B Qf;g}?.ky2%h');
define('NONCE_KEY',        'ikbT(iA!qNg[hF]#:{Ant;ImQ-V$#QH&h1>6-G<(-}p4riHDd2V;7|CvAV<n-0ZF');
define('AUTH_SALT',        '-r]KWx*Sw>AR;~hY`A`NB(h[pQ,z53:et<]r0Bz?a.kYniW#ileVU_|$)+&`!.tl');
define('SECURE_AUTH_SALT', '^~)dk@YcyN_?Bg4p/NzV6+&m *ncWgA]46&@I)8_kA/SFiZm|y>rbX?7.6rtxydZ');
define('LOGGED_IN_SALT',   'KZ%dLA20xw~,rEn(b7ZgV1&EvC*F:==t#A+dQJ3]pL)7,P.=*]mO-z6(JcNX#|I#');
define('NONCE_SALT',       '&%^U[_1Nk89c`loe%.Z)-&4sUb`u-{gB8lw^(*!lv@QPp1kb^i:ddM|@[8B3=m(:');

/**#@-*/

/**
 * WordPress database table prefix.
 *
 * You can have multiple installations in one database if you give each
 * a unique prefix. Only numbers, letters, and underscores please!
 */
$table_prefix = 'wp_';

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 *
 * For information on other constants that can be used for debugging,
 * visit the documentation.
 *
 * @link https://wordpress.org/support/article/debugging-in-wordpress/
 */
define( 'WP_DEBUG', false );

/* Add any custom values between this line and the "stop editing" line. */



/* That's all, stop editing! Happy publishing. */

/** Absolute path to the WordPress directory. */
if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

/** Sets up WordPress vars and included files. */
require_once ABSPATH . 'wp-settings.php';


上面wp-config. php文件要改的:
define( 'DB_NAME', '{DB_NAME}' );
define( 'DB_USER', '{DB_USER}' );
define( 'DB_PASSWORD', '{DB_PASSWORD}' );
define( 'DB_HOST', '{DB_HOST}' );

和访问https://api.wordpress.org/secret-key/1.1/salt/

在这里插入图片描述

三、wordpress迁移至k8s

1、Dockerfile

FROM centos:7
# 0、申明环境变量,便于后续的复用以及变更;
ENV Web_Dir="/usr/share/nginx/html/"
#
# 1、准备epel源、base源、并且安装nginx以及php、最后清理缓存、删除默认的nginx站点
RUN curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo && \
    rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm && \
    rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm && \
    echo "sslverify=false" >> /etc/yum.conf

RUN yum install nginx php71w-fpm php71w-xsl php71w php71w-ldap php71w-cli php71w-common php71w-devel php71w-gd php71w-pdo php71w-mysql php71w-mbstring php71w-bcmath php71w-mcrypt -y && \
     yum clean all && rm -rf /var/cache/yum/* && \
     rm -rf ${Web_Dir}


# 2、将代码存储到指定的路径下
COPY . ${Web_Dir}

# 3、准备nginx调用php的配置文件;-->抽离到configmap管理


# 4、修订权限;为了避免nginx和php运行的身份不一致,从而造成wordpress无法正常上传图片
RUN useradd -M www && \
    sed -i '/^user/c user www;' /etc/nginx/nginx.conf && \
    sed -i '/^user/c user = www' /etc/php-fpm.d/www.conf && \
    sed -i '/^group/c group = www' /etc/php-fpm.d/www.conf && \
    chown -R www.www ${Web_Dir} /var/lib/nginx/

# 5、暴露容器的端口
EXPOSE 80

# 6、启动脚本 nginx php 然后启动这个镜像会执行该脚本
COPY ./entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["bash","-c","/entrypoint.sh"]

2、启动脚本 entrypoint.sh

#运行Wordpress时,可以通过环境变量替换连接数据库相关信息。
Wordpress_File=/usr/share/nginx/html/wp-config.php

sed -i s/{DB_NAME}/${DB_NAME:-wordpress}/g ${Wordpress_File}
sed -i s/{DB_USER}/${DB_USER:-wordpress}/g ${Wordpress_File}
sed -i s/{DB_PASSWORD}/${DB_PASSWORD:-wordpress}/g ${Wordpress_File}
sed -i s/{DB_HOST}/${DB_HOST:-localhost}/g  ${Wordpress_File}


#启动php /nginx
php-fpm && \
nginx -g "daemon off;"

3、构建镜像 、打tag、推送镜像

docker build -t harbor.oldxu.net/base/wordpress:v6.0 . 
docker tag 9779eee harbor.oldxu.net/base/wordpress:v6.0
docker push harbor.oldxu.net/base/wordpress:v6.0  

4、DB服务

4.1 01-mysql-headless.yaml
apiVersion: v1
kind: Service
metadata:
  name: mysql-svc
spec:
  clusterIP: None
  selector:
    app: mysql
  ports:
  - port: 3306
    targetPort: 3306
4.2 02-mysql-statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  serviceName: "mysql-svc"
  replicas: 1
  selector:
    matchLabels:
      app: mysql
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - name: db
        image: mysql:5.7
        env:
        - name: MYSQL_ROOT_PASSWORD
          value: oldxu3957
        - name: MYSQL_DATABASE
          value: wordpress
        
        ports:
        - containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql/
        
      volumeClaimTemplates:
      - metadata:
          name: data
        spec:
          accessModes: ["ReadWriteOnce"]
          storageClassName: "nfs"
          resources:
            requests:
              storage: 6Gi       
进容器库,创库创表创用户密码,创权限等
nginx配置文件 blog.oldxu.net.conf 和转为configmap
server{
  listen 80;
  server_name _;
  root /usr/share/nginx/html;
  client_max_body_size 100m;

  location / {
    index index.php;
  }
  
  location ~ \.php$ {
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }
} 

#将配置转为 configmap

kubectl create configmap nginxconfs --from-file=blog.oldxu.net.conf
4.3 03-wordpress-secret.yaml (创建连接数据库secret) (dp.yaml会引用此secret)
apiVersion: v1
kind: Secret
metadata:
  name: wordpress-secret
stringData:
  DB_NAME: wordpress
  DB_USER: root
  DB_PASSWORD: oldxu3957
  DB_HOST: mysql-0.mysql-svc.default.svc.cluster.local 
#master执行
dig @10.96.0.10  mysql-0.mysql-svc.default.svc.cluster.local +short
4.4 04-wordpress-pvc.yaml (准备PVC共享图片) (dp.yaml会引用此pvc)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: wordpress-data
spec:
  storageClassName: "nfs"
  accessModes:
  - ReadWriteMany
  resources:
    requests:
      storage: 6Gi

5、wordpress服务

05-wordpress-dp.yaml
kubectl create secret docker-registry harbor-login --docker-server=xxx.net --docker-username=xx--docker-password=xxx
apiVersion: apps/v1
kind: Deployment
metadata:
  name: wordpress-dp
spec:
  replicas: 3
  selector:
    matchLabels:
      app: wordpress
  template:
    metadata:
      labels:
        app: wordpress
    spec:
      imagePullSecrets:
      - name: harbor-login
      containers:
      - name: wordpress
        image: harbor.oldxu.net/base/wordpress:v6.0
        ports:
        - containerPort: 80
        envFrom:
        - secretRef:
            name: wordpress-secret
        volumeMounts:
        - name: config
          mountPath: /etc/nginx/conf.d/
        - name: images
          mountPath: /usr/share/nginx/html/wp-content/uploads  
          
      volumes:
      - name: config
        configMap:
          name: nginxconfs
      - name: images
        persistentVolumeClaim:
          claimName: wordpress-data        
06-wordpress-svc.yaml
apiVersion: v1
kind: Service
metadata: 
  name: wordpress-svc
spec:
  selector:
    app: wordpress
  ports:
    - port: 80
      targetPort: 80
07-wordpress-ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: wordpress-ingress
spec:
  ingressClassName: "nginx"
  rules:
  - host: wordpress.oldxu.net
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: wordpress-svc
            port:
              number: 80

旧版本ingress:

#apiVersion: networking.k8s.io/v1
apiVersion: extensions/v1beta1    
kind: Ingress
metadata:
  name: wordpress-ingress
spec:
  ingressClassName: "nginx"
  rules:
  - host: wordpress.oldxu.net
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          serviceName: wordpress-svc
          servicePort: 80
          #service:
          #  name: wordpress-svc
          #  port:
          #    number: 80

访问

wordpress.oldxu.net:30080

在这里插入图片描述
在这里插入图片描述

思路图

在这里插入图片描述

END

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值