-
前端访问后端时,关闭后端接口,通过nginx转发
- 编写后端
# 控制层
@RestController
@RequestMapping("/user")
public class TestController {
@GetMapping("/test")
public String test(){
return "test success";
}
}
# yml
server:
port: 8080
- 部署后端,测试(未关闭8080端口,直接访问后端接口)
- 编写前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="http://124.222.5.107:8080/user/test">直接访问</a><br>
<a href="http://124.222.5.107:8005/user/test">请求转发</a>
</body>
</html>
- 放到如下目录
- 配置nginx
- 重启nginx,测试
- 未关闭8080端口,直接访问
- 未关闭8080端口,请求转发
- 关闭8080端口,请求转发
- 将后端项目打成镜像,在后端jar包所在目录编写Dockerfile
# 因为项目使用的java11
FROM chniny/java:11.0.12
VOLUME /tmp
# jar包名称
ADD app.jar /app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]
- 构建并启动
# 构建
docker build -t chniny/demo:4.0 .
# 启动容器
docker run -dit --restart=always --name demo -p 8080:8080 chniny/demo:4.0
# 不停止容器退出前台
ctrl + p + q
-
云服务器先放开8080端口,测试
- 使用内网
# 服务器创建网络
docker network create -d bridge my-bridge
# 将nginx添加到网络
docker network connect my-bridge nginx
# 将后端镜像添加到网络
docker network connect my-bridge demo
# 注意
# 如果使用如下方式启动后端镜像
docker run -it --net=host --name demo -p 8080:8080 chniny/demo:4.0
# 添加到自定义的网络时会报错
Error response from daemon: container sharing network namespace with another container or host cannot be connected to any other network
# 需使用入下方式
docker run -dit --restart=always --name demo -p 8080:8080 chniny/demo:4.0
# 查看nginx的网络
[root@VM-12-15-centos jar]# docker inspect 7b85604f7502 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.3",
"IPAddress": "172.17.0.3",
"IPAddress": "172.18.0.2",
# 查看后端镜像的网络
[root@VM-12-15-centos jar]# docker inspect 0c88ace83397 | grep IPAddress
"SecondaryIPAddresses": null,
"IPAddress": "172.17.0.4",
"IPAddress": "172.17.0.4",
"IPAddress": "172.18.0.3",
# 测试:后端ping nginx -> 成功
docker exec -it demo ping nginx
# 测试:nginx ping 后端-> 报错
docker exec -it nginx ping demo
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "ping": executable file not found in $PATH: unknown
# 清理此容器的网络占用(未使用)
docker network disconnect --force 网络模式 容器名称
docker network disconnect --force bridge nginx
- 前端index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="http://124.222.5.107:8080/user/test">直接访问</a><br>
<a href="http://124.222.5.107:8005/user/test">请求转发</a>
</body>
</html>
- index.html放到如下目录
- 配置nginx,并重启
-
云服务器关闭8080端口
- 直接访问
- 请求转发 -> 测试成功