Ubuntu 18.04 nginx + vue【前端】 +.net core 3.1【后端】 + mongodb环境部署
1. 更新系统apt-get updateapt-get upgrade2. 安装.net core SDK 3.1使用 APT 进行安装可通过几个命令来完成。 安装 .NET 之前,请运行以下命令,将 Microsoft 包签名密钥添加到受信任密钥列表,并添加包存储库。打开终端并运行以下命令:wget https://packages.microsoft.com/config/ubuntu/18
Ubuntu 18.04 nginx + vue【前端】 +.net core 3.1【后端】 + mongodb环境部署
1. 更新系统
apt-get update
apt-get upgrade
修改时区:
root@www:~# tzselect
Please identify a location so that time zone rules can be set correctly.
Please select a continent, ocean, "coord", or "TZ".
1) Africa
2) Americas
3) Antarctica
4) Asia
5) Atlantic Ocean
6) Australia
7) Europe
8) Indian Ocean
9) Pacific Ocean
10) coord - I want to use geographical coordinates.
11) TZ - I want to specify the time zone using the Posix TZ format.
#? 4
Please select a country whose clocks agree with yours.
1) Afghanistan 18) Israel 35) Palestine
2) Armenia 19) Japan 36) Philippines
3) Azerbaijan 20) Jordan 37) Qatar
4) Bahrain 21) Kazakhstan 38) Russia
5) Bangladesh 22) Korea (North) 39) Saudi Arabia
6) Bhutan 23) Korea (South) 40) Singapore
7) Brunei 24) Kuwait 41) Sri Lanka
8) Cambodia 25) Kyrgyzstan 42) Syria
9) China 26) Laos 43) Taiwan
10) Cyprus 27) Lebanon 44) Tajikistan
11) East Timor 28) Macau 45) Thailand
12) Georgia 29) Malaysia 46) Turkmenistan
13) Hong Kong 30) Mongolia 47) United Arab Emirates
14) India 31) Myanmar (Burma) 48) Uzbekistan
15) Indonesia 32) Nepal 49) Vietnam
16) Iran 33) Oman 50) Yemen
17) Iraq 34) Pakistan
#? 9
Please select one of the following time zone regions.
1) Beijing Time
2) Xinjiang Time
#? 1
The following information has been given:
China
Beijing Time
Therefore TZ='Asia/Shanghai' will be used.
Selected time is now: Mon Aug 17 16:13:15 CST 2020.
Universal Time is now: Mon Aug 17 08:13:15 UTC 2020.
Is the above information OK?
1) Yes
2) No
#? 1
You can make this change permanent for yourself by appending the line
TZ='Asia/Shanghai'; export TZ
to the file '.profile' in your home directory; then log out and log in again.
Here is that TZ value again, this time on standard output so that you
can use the /usr/bin/tzselect command in shell scripts:
Asia/Shanghai
root@www:~#
root@www:~# date
Mon Aug 17 01:14:10 PDT 2020
root@www:~# ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
root@www:~# date
Mon Aug 17 16:14:46 CST 2020
2. 安装.net core SDK 3.1
使用 APT 进行安装可通过几个命令来完成。 安装 .NET 之前,请运行以下命令,将 Microsoft 包签名密钥添加到受信任密钥列表,并添加包存储库。
打开终端并运行以下命令:
wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
安装 SDK
.NET Core SDK 使你可以通过 .NET Core 开发应用。 如果安装 .NET Core SDK,则无需安装相应的运行时。 若要安装 .NET Core SDK,请运行以下命令:
sudo apt-get update; \
sudo apt-get install -y apt-transport-https && \
sudo apt-get update && \
sudo apt-get install -y dotnet-sdk-3.1
3. 安装nginx
Append the appropriate stanza to /etc/apt/sources.list. If there is concern about persistence of repository additions (i.e. DigitalOcean Droplets), the appropriate stanza may instead be added to a different list file under /etc/apt/sources.list.d/, such as /etc/apt/sources.list.d/nginx.list
vi /etc/apt/sources.list.d/nginx.list
deb https://nginx.org/packages/ubuntu/ xenial nginx
deb-src https://nginx.org/packages/ubuntu/ xenial nginx
保存
apt-get install gnupg
apt-key adv --keyserver keyserver.ubuntu.com --recv-keys $key
apt-get update
出现问题
The following signatures couldn't be verified because the public key is not available: NO_PUBKEY ABF5BD827BD9BF62
解决
sudo gpg --keyserver keyserver.ubuntu.com --recv ABF5BD827BD9BF62 //(这个公钥根据提示来写的)
sudo gpg --export --armor ABF5BD827BD9BF62 | sudo apt-key add -
apt-get update
apt-get install nginx
文件位置
/usr/sbin/nginx :主程序
/etc/nginx :配置文件
/usr/share/nginx :存放静态文件
/var/log/nginx :存放日志
启动nginx
service nginx start # 启动nginx
nginx -t #检测配置
service nginx reload # 重新加载nginx配置文件
验证
浏览器输入:
127.0.0.1
- 配置/etc/nginx文件
安装的版本默认文件是 default.conf
需要做到这几点,http请求转发到https,后端调用通过代理转发到后端的url
server {
listen 80;
#server_name localhost;
server_name your_domain.com www.your_donmain.com;
rewrite ^(.*)$ https://$host$1 permanent;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
server {
listen 80;
#server_name localhost;
server_name houduan.your_domain.com;
rewrite ^(.*)$ https://$host$1 permanent;
#charset koi8-r;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
server {
listen 443 ssl;
server_name your_domain.com www.your_donmain.com;
ssl_certificate "/etc/letsencrypt/live/your_domain.com/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/your_domain.com/privkey.pem";
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location / {
root /***/;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass https://houduan.your_domain.com;
#proxy_pass http://127.0.0.1:5011;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_redirect default;
}
}
server {
listen 443 ssl; # redirect to https
server_name houduan.your_domain.com;
ssl_certificate "/etc/letsencrypt/live/your_domain.com/fullchain.pem";
ssl_certificate_key "/etc/letsencrypt/live/your_domain.com/privkey.pem";
location / {
proxy_pass http://XXX.XXX.XX.XXX:XXXX;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_redirect default;
}
}
配置完,检测配置,重新加载
nginx -t #检测配置
service nginx reload # 重新加载nginx配置文件
4. 打开防火墙
root@www:~# ufw allow ssh
root@www:~# ufw status
Status: inactiv
root@www:~# ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
ufw allow http
Rule added
Rule added (v6)
root@www:~# ufw allow 80/tcp
Skipping adding existing rule
Skipping adding existing rule (v6)
root@www:~# ufw allow https
Rule added
Rule added (v6)
root@www:~# ufw allow 443/tcp
Skipping adding existing rule
Skipping adding existing rule (v6)
root@www:~# ufw status
Status: active
To Action From
-- ------ ----
22/tcp ALLOW Anywhere
80/tcp ALLOW Anywhere
443/tcp ALLOW Anywhere
22/tcp (v6) ALLOW Anywhere (v6)
80/tcp (v6) ALLOW Anywhere (v6)
443/tcp (v6) ALLOW Anywhere (v6)
5. 域名注册解析
- 域名注册 :NAMESILO
- 域名注册向导:Namesio域名注册向导
- 域名解析:DNSPOD
6. 配置安全证书https
安装Certbot
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt install python-certbot-nginx
使用Certbot获取免费SSL证书
$ sudo certbot --nginx -d example.com -d www.example.com
–nginx 选项指明使用nginx插件,生成证书后certbot会修改nginx/sites-available/default中的路由配置文件,如果希望手动更改路由配置可以再生成证书时选择[1]。
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
-------------------------------------------------------------------------------
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
-------------------------------------------------------------------------------
Select the appropriate number [1-2] then [enter] (press 'c' to cancel):
证书自动重申
$ sudo certbot renew --dry-run
添加定时任务,使证书到期自动更新
crontab e
3 */12 * * * certbot renew --dry-run
7. 发布后端webapi
在本地开发环境,编译发布
dotnet.exe publish D:\work_doc\Test\asp\BooksApi/BooksApi.csproj /property:GenerateFullPaths=true /consoleloggerparameters:NoSummary
编译后的文件在目录 *** Debug\netcoreapp3.1\publish\,压缩打包成zip文件
使用winSCP上传到服务器,然后解压 :unzip 文件名称
在远程服务器上,运行
dotnet /usr/share/nginx/guanliapi/BooksApi.dll
排错
(1) line 207 var appSettings = appSettingsSection.Get ();获取空值
解决方法:
参考:给IConfiguration写一个GetAppSetting扩展方法
(2)line 298 System.IO.DirectoryNotFoundException: /files/Images/
解决方法:
考虑到api端静态文件没使用到,暂时注释掉。
(3)System.ArgumentNullException: Value cannot be null. (Parameter ‘connectionString’)
Microsoft.EntityFrameworkCore.SqlServerDbContextOptionsExtensions.UseSqlServer(DbContextOptionsBuilder optionsBuilder, String connectionString, Action`1 sqlServerOptionsAction)
解决方法:
数据库调用出错, DbContext没有使用到,把跟此相关的全部注释掉。
最后显示可以正常运行。
- 如果可以运行成功,就直接创建成服务
#服务名称自定义
vi /etc/systemd/system/kestrel-mywebsite.service
键入以下内容
[Unit]
Description=MyWebSite a .NET Core Web App running on Ubuntu
[Service]
WorkingDirectory=/var/www/MyWebSite
ExecStart=/usr/bin/dotnet /var/www/MyWebSite/MyWebSite.dll
Restart=always
RestartSec=10
SyslogIdentifier=dotnet-mywebsite
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target
其中,WorkingDirectory和ExecStart替换成自己的上传目录和dll,RestartSec为该服务崩溃后重启前等待秒,SyslogIdentifier为系统日志标识符,User为启动用户
保存并启用服务
#开机启动.NET服务
systemctl enable kestrel-mywebsite.service
#启动.NET服务
systemctl start kestrel-mywebsite.service
#检查服务是否正常运行
systemctl status kestrel-mywebsite.service
#检查网站是否正常访问,正常将会返回200
curl -I localhost:5000
#更新重新上传dll需重启服务
systemctl restart kestrel-mywebsite.service
#查看端口占用
lsof -i:80
重启Nginx
#检查配置文件错误
nginx -t
#重启nginx
nginx -s reload
访问http://server_IP_address
就能看到部署好的网站了
参考文档:在Ubuntu 18.04上使用Nginx部署ASP.NET Core Web应用
8. 安装mongodb,开启认证并添加用户,备份还原
- 安装
apt-get install mongodb
service mongod restart
提示:
Failed to restart mongod.service: Unit mongod.service not found.
解决:
vi /etc/systemd/system/mongodb.service
[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
[Service]
User=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
[Install]
WantedBy=multi-user.target
- 分别输入下面的两个命令可以启动服务并检查其状态
sudo systemctl start mongodb
sudo systemctl status mongodb
提示:
● mongodb.service - An object/document-oriented database
Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
Active: failed (Result: exit-code) since Mon 2020-08-17 16:54:22 CST; 4s ago
Docs: man:mongod(1)
Process: 19192 ExecStart=/usr/bin/mongod --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS (code=exited, status=100)
Main PID: 19192 (code=exited, status=100)
Aug 17 16:54:18 www systemd[1]: Started An object/document-oriented database.
Aug 17 16:54:22 www systemd[1]: mongodb.service: Main process exited, code=exited, status=100/n/a
Aug 17 16:54:22 www systemd[1]: mongodb.service: Failed with result 'exit-code'.
r
解决:
root@www:/run# chown -R mongodb:mongodb /var/lib/mongodb
root@www:/run# systemctl start mongodb
root@www:/run# systemctl status mongodb
● mongodb.service - An object/document-oriented database
Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2020-08-17 16:59:54 CST; 2s ago
Docs: man:mongod(1)
Main PID: 19477 (mongod)
Tasks: 3 (limit: 422)
CGroup: /system.slice/mongodb.service
└─19477 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf
Aug 17 16:59:54 www systemd[1]: Started An object/document-oriented database.
- 开启认证,添加用户
设置用户
建议在开启认证前创建用户,创建一个超级用户或者对应的数据库用户后,再开启认证并且重启,mongoDB
- 创建超级用户
进入mongo命令行面板,进入admin数据库
use admin
创建账户
db.createUser(
{
user: "userName",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
user:用户名
pwd:密码
role:userAdminAnyDatabase 超级权限
admin:账户对应的数据库
查看用户
进入要查看的数据库
use admin
查看用户
show users
➢ 创建普通用户
进入数据库,比如test
use test
创建用户
db.createUser(
{
user: "userName",
pwd: "password",
roles: [ { role: "readWrite", db: "test" } ]
}
)
readWrite:读写权限
➢ role规则
Read:允许用户读取指定数据库
readWrite:允许用户读写指定数据库
dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读写权限
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限
root:只在admin数据库中可用。超级账号,超级权限
➢ 开启认证
进入服务器下的etc目录
cd /etc
编辑mongodb.conf文件
vi mongodb.conf
把auth改为true
auth = true
➢ 重启mongo
关闭/启动
sudo service mongodb stop
sudo service mongodb start
➢ node mongose 连接数据库
mongo未开启认证时
mongodb://localhost/dataBase
或者
mongodb://127.0.0.1/dataBase
dataBase为数据库的名称
如果mongo开启了认证
连接方式为
mongodb://userName:password@localhost/dataBase
加上当前数据库用户名userName和密码password即可
-
若要开放远程连接,在MongoDB的配置文件中将bindIp从127.0.0.1修改为0.0.0.0即可,MongoDB的配置文件的目录为/etc/mongod.conf。
-
windows mongodb添加认证和用户
添加用户
use admin
db.createUser({user:"admin",pwd:"password",roles:[{"role":"userAdmin","db":"admin"},{"role":"root","db":"admin"},{"role":"userAdminAnyDatabase","db":"admin"}]})
use test
db.createUser({user:"user",pwd:"password",roles:[{"role":"readWrite","db":"test"}]})
开启认证方式启动,并添加到windows服务
添加
mongod --logpath="d:\mongodb\data\mongod.log" --logappend --dbpath="d:\mongodb\data\db" --port 27017 --auth --serviceName “demoMongod” --serviceDisplayName MongoDB --install
删除
mongod --logpath="d:\mongodb\data\mongod.log" --logappend --dbpath="d:\mongodb\data\db" --port 27017 --auth --serviceName “demoMongod” --serviceDisplayName MongoDB --remove
连接验证
mongo
use admin
db.auth("admin", "password")
1
或者
mongo -u admin -p password localhost:27017/admin
- mongodb数据自动备份
编写脚本:
#!/bin/bash
#backup MongoDB
#mongodump命令路径
DUMP=mongodump
#备份存放路径
TAR_DIR=/mnt/bklist
#获取当前系统时间
DATE=`date +%Y_%m_%d`
#数据库账号
DB_USER=xxxxxx
#数据库密码
DB_PASS=xxxxxx
#DAYS=15代表删除15天前的备份,即只保留近15天的备份
DAYS=7
#最终保存的数据库备份文件
TAR_BAK="mongodb_bak_$DATE.gz"
$DUMP -h 192.168.200.202:27017 -u $DB_USER -p $DB_PASS --authenticationDatabase "admin" -d "kyb-main" --gzip --archive=$TAR_DIR/$TAR_BAK
#删除7天前的备份文件
find $TAR_DIR/ -mtime +$DAYS -delete
exit
添加定时任务:
crontab -e
3 */12 * * * sh /data/mongodb_bakup.sh #每天12时3分备份一次
cron服务是Linux的内置服务,但它不会开机自动启动。可以用以下命令启动和停止服务:
service cron start
service cron stop
service cron restart
service cron reload
service cron status
如果未能正常使用以以下命令启用服务
sudo systemctl enable cron.service;
sudo systemctl start cron.service
- 数据库还原
解压
gunzip 压缩文件
mongorestore -h <hostname><:port> -d dbname <path>
–host <:port>, -h <:port>:
MongoDB所在服务器地址,默认为: localhost:27017
–db , -d :
需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2
–drop:
恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用哦!
mongorestore 最后的一个参数,设置备份数据所在位置,例如:c:\data\dump\test。
你不能同时指定
–dir:
指定备份的目录
你不能同时指定
9. 发布前端vue
在开发环境下,编译准备好的源码:
npm run build
编译后,待发布的文件会集中到一个文件夹,这是在vue.config.js中定义【publicPath】,比如 dist/configtest
vue cli下 :vue.config.js的配置参考
把待发布文件上传到nginx服务器
访问http://域名
10. 测试
错误:
- 调用api报500错误
Error: Internal Server Error
Response body
Download
{
"type": "error:format",
"title": "Format",
"status": 500,
"detail": "Element 'add_timesta' does not match any field or property of class .",
"instance": "/api/user/get_dynamic_list"
}
解决方法:
经过检查,原因是数据库表的element元素在迁移时出错。‘add_timesta’ 原本是add_timestamp, 还有很多少了,迁移时用客户端navicat导入导出,可能过程中出错了。
改用mongodb备份/还原命令
备份:
mongodump -h dbhost -d dbname -o dbdirectory
还原
mongorestore -h <:port> -d dbname
- 刷新页面报404错误
解决方法:
修改nginx配置文件
location / {
root ...
index ...
try_files $uri $uri/ /index.html; ---解决页面刷新404问题
}
将上面代码放入nginx配置文件中
保存退出
. ./nginx -t – 验证nginx配置文件是否正确
. ./nginx -s reload – 重启nginx
记得修改完nginx配置文件一定要重启nginx 不然没有效果!!!
更多推荐
所有评论(0)