[root@master nginx]# kubectl get nodes -o wide
[root@master nginx]# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1443/TCP 25h
tomcatservice NodePort 10.102.227.688080:30010/TCP 128m
这里可以看到,集群中已经有一个tomcat集群,cluster-ip是 10.102.227.68 ,外部访问端口为30010,内部通讯端口为:8080。通过192.168.206.138:30010可以打开tomcat的欢迎界面。
这里要增加一个Nginx服务,并成功代理到tomcat页面中去。
tomcat服务怎么启动,请看:k8s 使用tomcat官方镜像部署集群并解决访问页面404-CSDN博客
docker pull nginx
docker tag docker.io/nginx:latest nginx:v1
cat nginx.conf
############################################
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
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;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /tomcat/ {
proxy_pass http://10.102.227.68:8080/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
其中:
新增了一个location,代理到tomcat clusterip的8080
location /tomcat/ {
proxy_pass http://10.102.227.68:8080/;
}
cat Dockerfile
############################################
FROM nginx:v1
RUN rm -rf /etc/nginx/nginx.conf
ADD ./nginx.conf /etc/nginx/
执行创建镜像命令:
docker build -t nginx:v3 .
docker tag nginx:v3 192.168.206.137/library/nginx:v3
docker push 192.168.206.137/library/nginx:v3
要注意:在单台服务器上创建的image,使用K8s部署时,其他节点默认是获取不到这个镜像的,会导致发布失败。
在镜像创建完成之后,最好现在docker里面启动一下试试。但是要注意的是,nginx官方镜像在k8s和docker集群中自动会起来。但是上面通过dockerfile创建的镜像,在docker调试时需要docker exec进入后执行:nginx 。
vim nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deploy
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: mynginx
image: 192.168.206.137/library/nginx:v3
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: nginxservice
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
nodePort: 30080
selector:
app: nginx
要注意:
1,image: 192.168.206.137/library/nginx:v3,必须要配置harbor的完整路径,保证集群内的服务器都可以自动下载改镜像。否者会报错找不到image
2,nodePort: 30080,这个nodePort定义的是外部访问端口,取值在30000--32767,不自定义的话,系统会默认分配一个此区间内未使用的端口。如果定义的值不在此区间会报错:
The Service "nginxservice" is invalid: spec.ports[0].nodePort: Invalid value: 80: provided port is not in the valid range. The range of valid ports is 30000-32767
kubectl create -f nginx.yaml
完成之后检查相关信息:
kubectl get svc
kubectl get nodes -o wide
kubectl get pods -o wide
如下:
通过上图可以看到,nginx默认部署在了master节点 192.168.206.138,使用:
http://192.168.206.138:30080/tomcat/
即可成功访问到tomcat服务的欢迎界面