项目部署服务器记录

linux 部署项目

使用 centos 7 系统部署

nginx 部署前端

安装依赖

yum -y install gcc gcc-c++ make libtool zlib zlib-devel openssl openssl-deve

安装 nginx

yum -y install n

修改nginx配置

vim /etc/nginx/nginx.conf
// 修改 nginx 用户 user root
// 选择项目地址
// location下 root :项目文件地址
// 刷新配置
nginx -s reload

安装java

yum install -y java-1.8.0-openjdk*

运行jar包

java -jar ./user-center-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

#后台运行
nohup java -jar ./user-center-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod & 

安装配置数据库 mysql

安装 mysql

yum install mysql mysql-server mysql-devel

启动mysql

systemctl start mysqld

设置开机启动

systemctl enable mysqld

进入mysql

mysql -u root

设置密码

// 方法1
set password for 'root'@'localhost' =password('密码');
// 方法2
alter user 'root'@'localhost' identified  by '密码';

创建用户远程连接 (这里用户fantasy)

create user fantasy@'%' identified by '密码';
grant all privileges on *.* to fantasy@'%' with grant option;

flush privileges;

数据库默认编码改utf-8

vim /etc/my.cnf
[mysqld]
character_set_server=utf8;
init_conntent='SET NAMES uft8'

// 重启服务
systemctl restart mysqld

docker部署

安装docker

yum -y install docker
# 开机启动 docker
systemctl enable docker
systemctl start docker
# 配置国内源
sudo vim /etc/docker/daemon.json
{
 "registry-mirrors":["https://6kx4zyno.mirror.aliyuncs.com","https://docker.mirrors.ustc.edu.cn/"]
}
systemctl daemon-reload
systemctl restart docker

Docker 中配置 MySQL

  1. 拉取 MySQL 镜像:
    docker pull mysql:latest
    
  2. 创建 MySQL 容器:
    docker run --name my-mysql -e MYSQL_ROOT_PASSWORD=<your_password> -p 3306:3306 -d mysql:latest
    
  3. 进入 MySQL 容器:
    docker exec -it my-mysql bash
    
  4. 在容器内使用 MySQL 客户端连接 MySQL 服务:
    mysql -uroot -p<your_password>
    
    其中 <your_password> 需要替换为你设置的 MySQL root 用户密码。
  5. 在 MySQL 命令行中执行 SQL 语句,例如创建一个数据库和表:
    CREATE DATABASE testdb;
    USE testdb;
    CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(50), age INT);
    INSERT INTO users (name, age) VALUES ('Alice', 25);
    INSERT INTO users (name, age) VALUES ('Bob', 30);
    SELECT * FROM users;
    

要在 MySQL 中新建一个可以远程连接的用户
创建一个新用户并授权远程访问:

CREATE USER 'newuser'@'%' IDENTIFIED BY '<user_password>';
GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

其中 newuser 是你要创建的新用户名,<user_password> 是新用户的密码。% 表示允许任何 IP 地址进行远程连接

把启动流程 的命令写入 Dockerfile

FROM 依赖的基础镜像
WORKDIR 工作目录
COPY 从本机复制文件
RUN 执行命令
CMD / ENTRYPOINT(ENTRYPOINT可附加额外参数)指定运行容器时默认执行的命令

后端 Dockerfile

FROM maven:3.5-jdk-8-alpine as builder
# Copy local code to the container image.
WORKDIR /app
COPY pom.xml .
COPY src ./src
# Build a release artifact.
RUN mvn package -DskipTests
# Run the web service on container startup.
CMD ["java","-jar","/app/target/user-center-0.0.1-SNAPSHOT.jar","--spring.profiles.active=prod"]

构建docker镜像

docker build -t user-center-backend:v0.0.1 .

运行docker run

docker run -p 8080:8080 user-center-backend:v0.0.1

前端 Dockerfile

FROM nginx
WORKDIR /usr/share/nginx/html/
USER root
COPY ./docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY ./dist /usr/share/nginx/html/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
docker build -t user-center-front:v0.0.1 .
docker run -p 80:80 -d user-center-frontend:v0.0.1

注意:在 docker 容器里的 nginx 要配置转发的地址最好写域名或公网 ip ,localhost会找不到

docker 常用命令

# 进入容器
docker exec -i -t 容器名/id /bin/bash
# 查看进程
docker ps
# 查看日记
docker logs -f 容器名/id
# 杀死容器
docker kill 容器名/id
# 强制删除容器
docker rmi -f 容器名/容器id

其他部署方法

  1. linux 安装宝塔面板 可视化部署项目 参考连接
  2. 前端页面 腾讯云 web 应用托管 参考连接
  3. 微信云托管 参考连接

跨域问题

方法一:

把前后端域名的和端口改成相同

通过 nginx进行转发

例如项目部署到同一台服务器,前端是 80 端口 后端是 8080端口

访问登陆页 http://test.user-center.com/user/login 转发到前端

访问请求接口api http://test.user-center.com/api/user/login 转发到后端

nginx 配置

vim /etc/nginx/nginx.conf
# 加入 下面内容
# 理解的是访问 xxx/api 的回转发到8080端口的 /api
location ^~ /api/ {
proxy_pass http://127.0.0.1:8080/api/;
}

前端请求baseURL配置成服务器地址默认端口80 即可

例如

const request = extend({
credentials: 'include', // 默认请求是否带上cookie
prefix: process.env.NODE_ENV === 'production' ?\
  'http://test.user-center.com' : undefined,
});

方法二

让服务器告诉浏览器:允许跨域(返回 Access-Control-Allow-Origin 响应头)

nginx 配置文件加入

location ^~ /api/ {
  proxy_pass http://127.0.0.1:8080/api/;
  add_header 'Access-Control-Allow-Origin' $http_origin;
  add_header 'Access-Control-Allow-Credentials' 'true';
  add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
  add_header Access-Control-Allow-Headers '*';
  if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Origin' $http_origin;
    add_header 'Access-Control-Allow-Methods' 'GET, POST,OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Max-Age' 1728000;
    add_header 'Content-Type' 'text/plain; charset=utf-8';
    add_header 'Content-Length' 0;
  	return 204;
  }
}

方法三

后端配置

方式一: 配置 @CrossOrigin 注解 在Controller加上

@CrossOrigin(origins = { "http://user.code-nav.cn"},allowCredentials = "true")

方式二: 添加 web 全局请求拦截器

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    //设置允许跨域的路径
    registry.addMapping("/**")
      //设置允许跨域请求的域名
      //当**Credentials为true时,**Origin不能为星号,需为
      /具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
      .allowedOrigins("http://localhost:9527",
                      "http://127.0.0.1:9527", "http://127.0.0.1:8082",
                      "http://127.0.0.1:8083")
      //是否允许证书 不再默认开启
      .allowCredentials(true)
      //设置允许的方法
      .allowedMethods("*")
      //跨域允许时间
      .maxAge(3600);
  }
}

方式三: 定义新的 corsFilter Bean,参考:https://www.jianshu.com/p/b02099a435bd

cookie 问题

方法1:前端配置代理

参考连接 https://blog.csdn.net/nineqblot/article/details/129905115

export default defineConfig({
  server: {
    proxy: {
      '/api': { // 请求接口中要替换的标识
        target: 'http://59.110.12.230:8080/', // 代地址
        changeOrigin: true, // 是否允许跨域
        secure: true,
        rewrite: (path) => path.replace(/^\/api/, '')// api标志替换为''
      }
    }
  },
})

axios bash url

axios.create({
    baseURL: '/api',
});

方法2:后端配置

参考 连接 连接

方法3:nginx 代理

location /api {
  proxy_pass http://localhost:8080/api/;
}

方法 4 :spring boot yml配置

server:
  port: 8080
  servlet:
    context-path: /api
    session:
      cookie:
        same-site: none
        http-only: true
        secure: true
        domain: localshot