AWS EC2配置Node和Python的线上环境

本地的Webapp搭建完成,自然要送到外网上,是骡子是马遛一遛先,于是自然而然地选择了拥有一年免费试用权的AWS EC2服务器。闲话少叙,直接上配置(账号申请步骤略去,只需要有有效的Email、信用卡和手机号即可):

一 初见EC2

  1. 进入EC2控制台后,首先选择EC2节点的地域,目测并没有中国相关的可以选,我先选择了新加坡节点,后来发现并不好用,于是选择了首尔节点。


    选择区域
  2. 依次完成以下步骤:


    启动实例
  3. 选择实例类型


    选择实例类型

    默认走起

    点击启动
  4. 配置秘钥


    选择“创建新密钥对”

    填写密钥对名称并下载,然后启动实例

    wellDone

    可以查看实例状态

    至此,免费的EC2实例搞定!

二 配置EC2

  1. 连接EC2
chmod 400 devildi.pem

ssh -i "devildi.pem" ec2-user@ec2-13-124-88-25.ap-northeast-2.compute.amazonaws.com

sudo passwd root #进入EC2后配置root用户,密码需要输入两次
exit #退出root用户
  1. 安装nvm
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh | bash

source ~/.bashrc

nvm install 14
  1. 安装配置Nginx
//安装
sudo yum install nginx
//配置

cd /etc/nginx 
sudo vim nginx.conf

//配置文件如下:
user root;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}
http {
    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;

    map $http_upgrade $connection_upgrade {
      default upgrade;
      ' '   close;
     }
     upstream websocket {
      ip_hash;
      server localhost:4000;
     }
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    server {
        listen       80;
        listen       [::]:80;
        server_name  nextsticker.cn;
        root         /home/ec2-user/mywork/build;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
        location / {
           try_files $uri /index.html =404 ;
           add_header   Cache-Control no-cache;
           expires      1d;
       }
       location /api/ {
           proxy_pass http://127.0.0.1:4000;
       }
        location /socket.io {
            proxy_pass http://localhost:4000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade; #此处配置 上面定义的变量
            proxy_set_header Connection $connection_upgrade;
        }
        error_page 404 /404.html;
            location = /40x.html {
        }
        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
    # Settings for a TLS enabled server.
#
    server {
        listen       443 ssl http2;
        listen       [::]:443 ssl http2;
        server_name  nextsticker.cn;
        root         /home/ec2-user/mywork/build;
#
        ssl_certificate "/home/ec2-user/mywork_backend/Nginx/nextsticker.cn.crt";
        ssl_certificate_key "/home/ec2-user/mywork_backend/Nginx/nextsticker.cn.key";
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  10m;
     #   ssl_ciphers PROFILE=SYSTEM;
        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;
#
        location / {
           index  index.html index.htm;
           try_files $uri /index.html =404 ;
           add_header   Cache-Control no-cache;
           expires      1d;
        }
        location /api/ {
           proxy_pass http://127.0.0.1:4000;
        }
        location /socket.io {
            proxy_pass http://localhost:4000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade; #此处配置 上面定义的变量
            proxy_set_header Connection $connection_upgrade;
        }
        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}
//重启Nginx
sudo service nginx restart
//删除Nginx
sudo yum remove nginx
  1. 安装git并clone项目
sudo yum install git
git clone https://github.com/devildi/nt-koa.git
  1. 安装配置mongodb
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-amazon-3.2.7.tgz
tar -zxvf mongodb-linux-x86_64-amazon-3.2.7.tgz
mkdir -p mongodb/data
mkdir -p mongodb/log
touch /home/ec2-user/mongodb/log/master.log
touch /home/ec2-user/mongodb/master.pid
cd mongodb-linux-x86_64-amazon-3.2.7
sudo vim config.conf

//在config.conf文件中编辑
dbpath=/home/ec2-user/mongodb/data
logpath=/home/ec2-user/mongodb/log/master.log  
pidfilepath=/home/ec2-user/mongodb/master.pid  
directoryperdb=true  
logappend=true  
#replSet=testrs  
bind_ip=127.0.0.1
port=27017  
oplogSize=10000  
fork=true  
noprealloc=true  

#启动mongod服务
./bin/mongod -f config.conf

//本地数据备份到本地
sudo ./bin/mongodump -h 127.0.0.1:27017 -d davinci -o /Users/apple/Desktop/projects/mywork_backend/database -u woody -p ******
//云端数据库备份到本地
sudo ./bin/mongodump -h 54.180.82.174:27017 -d davinci -o /Users/apple/Desktop/projects/mywork_backend/database -u woody -p ******
//本地数据恢复
./bin/mongorestore -h 127.0.0.1:27017 -d davinci /Users/apple/Desktop/projects/mywork_backend/database/davinci -u woody -p ****** --drop
//云端数据库数据恢复
./bin/mongorestore -h 54.180.82.174:27017 -d davinci /Users/apple/Desktop/projects/mywork_backend/database/davinci -u woody -p ****** --drop

安装数据库时可能会遇到如下错误:

error while loading shared libraries: libssl.so.10: cannot open shared object file: No such file or directory

解决方案:

wget https://vault.centos.org/centos/8/AppStream/x86_64/os/Packages/compat-openssl10-1.0.2o-3.el8.x86_64.rpm

rpm -ivh compat-openssl10-1.0.2o-3.el8.x86_64.rpm --nodeps --force
  1. 安装PM2
npm install pm2 -g

pm2 start app.js -i max#启动服务

pm2 list #查看所有进程

pm2 stop all #关闭所有进程
  1. 配置EC2 入口策略
    选择安全组


    选择安全组

    添加入站策略
  2. 阿里云域名解析
    11.11买的域名,一年十几块钱:


    阿里云注册域名
  3. 配置Python开发环境之切换Python默认版本为3.x

sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 100
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 150
sudo update-alternatives --config python

10.安装配置Python的守护进程工具:Supervisor

pip install supervisor #安装
mkdir /etc/supervisor
echo_supervisord_conf > /etc/supervisor/supervisord.conf
#生成supervisor配置文件,位置在:/etc/supervisor/supervisord.conf

vim /etc/supervisor/supervisord.conf
#去掉“;”,“;”相当于注释
[include]
files = /etc/supervisor/config.d/*.conf

#在/etc/supervisor/config.d文件夹下新建项目的.conf配置文件,每个文件管理一个进程:
mkdir /etc/supervisor/config.d
vim grpc.conf

[program:grpc]   #grpc 为程序的名称
command=python server.py #需要执行的命令
directory=/home/ec2-user/mywork_backend/GRPC  #命令执行的目录
user=root #用户
stopsignal=INT
autostart=true #是否自启动
autorestart=true #是否自动重启
startsecs=3 #自动重启时间间隔(s)
stderr_logfile=/home/ec2-user/ossoffical.err.log #错误日志文件
stdout_logfile=/home/ec2-user/ossoffical.out.log #输出日志文件

#启动supervisor
supervisord -c /etc/supervisor/supervisord.conf

#查看进程状态
supervisorctl
grpc    RUNNING   pid 20732, uptime 0:17:52#输出显示grpc正在运行中
#当端口被占用时
ps -ef |grep supervisor
kill -9 端口号#

11.配置root用户

sudo passwd root#必须要要在ec2-user用户下执行
#按照提示输入两次密码即可
su root#输入密码即可切换到root用户
su ec2-user#切换到普通用户

大功告成

浏览器输入nextsticker.cn或者https://nextsticker.cn,成功访问!

成功访问

附录

将本地项目上传至github

  1. 删除本地仓库rm -rf .git
  2. 在本地项目根目录下git init
  3. git add .
  4. git status
  5. git commit,若出现了很多红色文件,那么就需再次进git add .
  6. git remote add origin+这个项目的github地址 ,当出现fatal: remote origin already exists.时,使用此命令git remote rm origin即可
  7. git push -u origin master

搞定收工!

为mongodb增加安全措施

部署于AWS EC2的mongodb中的数据“离奇失踪”了,但是多了一份Readme数据表,打开一看:

勒索文件

结合搜索引擎的结果来看,我的部署在公网的裸奔数据库怕是受到攻击了,于是亡羊补牢:为mongodb添加用户权限。

  1. 修改ip地址
    默认值(0.0.0.0)是所有的IP地址都能访问,该参数指定MongoDB对外提供服务的绑定IP地址,用于监听客户端 Application的连接,客户端只能使用绑定的IP地址才能访问mongod,其他IP地址是无法访问的。
    当在config.conf中修改bind_ip=127.0.0.1时,数据库仅本机访问,这里将此句注释。
  2. 修改默认mongodb TCP端口
    登录时需要./bin/mongo -port ****
  3. 创建管理员用户
#登录数据库
./mongo 
use admin
db.createUser({user:"devildi", pwd:"**********",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})

其中,userAdminAnyDatabase为授予在所有数据库上管理User的权限,然后在admin库下进行授权:db.auth('devildi','******'),当返回值为1时,就可以对其他业务数据库授权了。

  1. 创建单个数据库管理员
use nt
db.createUser({user:"woody", pwd:"******",roles:[{role:"readWrite",db:"nt"}]})
show users
#即用户woody对nt数据库有读写权限
  1. 开启权限认证
    config.conf中添加auth=true
  2. 重启mongod服务
pkill mongod
./bin/mongod -f config.conf
  1. 登录nt数据库
./mongo 127.0.0.1:27017/nt -u woody -p ******

通过Studio 3T链接AWS的mongodb

在终端建立 SSH 隧道:

//这里使用 27018 作为本地转发端口
ssh -N -L 27018:localhost:27017 ec2-user@your-aws-ip -i your-key.pem 

在 Studio 3T 中配置连接:


简单配置

由于AWS的mongodb配置了127.0.0.1本机访问,固可以通过SSH隧道的方式加密访问,安全性有所保障!

通过PM2脚本启动node服务

//在production.yaml中编辑:
apps:
  - script: ./SSR/server.js
    name: woody 
    env_production:
      NODE_ENV: production
      HOST: localhost

之后可以通过pm2 start production.yaml命令启动脚本。

当在AWS构建项目失败时

AWS的免费服务器由于其配置过低,nom run build时会大概率导致内存用尽的情况,导致项目构建失败,此时可以按照以下步骤进行配置:

# 创建1GB交换文件(根据你的磁盘空间调整大小)
sudo fallocate -l 1G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile

# 永久保留交换文件
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# 验证交换空间
free -h

构建时永久增加Node内存限制

NODE_OPTIONS=--max-old-space-size=4096 npm run build

以上的步骤大概率可以解决问题!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容