关于javascript:阿里云服务器建站指南

6次阅读

共计 10967 个字符,预计需要花费 28 分钟才能阅读完成。

起步

先在阿里云官网 [https://www.aliyun.com] 抉择适宜本人的云服务器 ECS,而后依照购买流程走即可。

购买结束,就能够应用你的服务器了。点击控制台,再抉择左侧栏的云服务器 ECS,就能够进到云服务器控制台。

点击左侧栏的实例,初始化一下明码。初始化后须要重启一下。

明码初始化后就能够近程连贯服务器了。(倡议明码设置得简单一些,本人之前因为明码设置得过于简略而被其他人登录过)

装置 git

在服务器上安装 git 能够让你很不便地更新代码,部署服务。

sudo wget https://www.kernel.org/pub/software/scm/git/git-2.8.0.tar.gz

下载相干依赖

sudo yum -y install zlib-devel openssl-devel cpio expat-devel

解压

sudo tar -zxvf git-2.8.0.tar.gz

编译

cd git-2.8.0
make configure
./configure
make
make install
echo "export PATH=$PATH:/usr/local/git/bin" >> /etc/bashrc
source /etc/bashrc  

在这些过程中可能会呈现一些谬误,

  autoconf: command not found (centos 6.7 install git-2.10.0 from source code)  
    解决办法:yum  install autoconf
  make[1]: *** [perl.mak] Error 2 
    解决办法:yum install perl-ExtUtils-MakeMaker package
  
  git clone 呈现 https 谬误:(从新编译即可)
    解决办法:
  yum install curl-devel
  cd home/developer/setup/git-2.8.0 // 这里就是到放 git 的中央就好
    ./configure
  make
    make install

装置 node.js

笔者次要钻研前端,所以服务端语言以 node.js 为主。

如何装置 node.js 能够参见阿里云文档,能够批改版本为较新的 node.js 版本,当然也能够应用 nvm 来治理 node.js 的版本。

装置完 node.js 当前,咱们略微批改一下 node.js 官网文档的例子,来启动一个 http 服务器。

代码如下

// server.js
const http = require('http');

const hostname = '0.0.0.0';
const port = 3001;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello, World!\n');
});

server.listen(port, hostname, () => {console.log(`Server running at http://${hostname}:${port}/`);
});

启动服务器

[root@iZ8vbfhrv1vsbp44n9fdtoZ start]# node server.js
Server running at http://0.0.0.0:3001/

你还须要增加平安组规定,关上服务器防火墙上的 3001 端口。具体操作如下

在实例列表页点击 ” 更多 ”, 找到平安组配置

点击配置规定

点击疾速创立规定

具体配置如下

配置结束后,就能够调用接口了。

mysql

要解决一些业务数据,mysql 是必须的。

下载

应用 yum 下载

wget -i -c http://dev.mysql.com/get/mysql57-community-release-el7-10.noarch.rpm
yum -y install mysql57-community-release-el7-10.noarch.rpm
yum -y install mysql-community-server

速度比较慢,须要急躁期待。

启停 mysql 服务

启动

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# systemctl start  mysqld.service

应用 ps -ef | grep mysql 查看,发现 mysql 服务曾经启动了。

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# ps -ef | grep mysql
mysql    21709     1  6 10:58 ?        00:00:00 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
root     21738 21649  0 10:58 pts/0    00:00:00 grep --color=auto mysql

进行

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# systemctl stop  mysqld.service

mysql 服务进行了

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# ps -ef | grep mysql
root     21747 21649  0 10:58 pts/0    00:00:00 grep --color=auto mysql
[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# systemctl start  mysqld.service

重设 root 明码,设置近程登录权限

先设置免密登录

vim /etc/my.cnf

在 mysqld 上面增加
skip-grant-tables

保留后重启 mysql,这时就能够跳过明码来登录 mysql 了

systemctl stop  mysqld.service
systemctl start  mysqld.service
mysql

先刷新

mysql>flush privileges;

创立用户

mysql>create user 'root'@'localhost' identified by '你的明码';

容许 root 用户近程登录

mysql>grant all privileges on *.* to 'root'@'%' identified by '你的明码';

刷新

mysql>flush privileges;

去掉 my.cnf 里的免密设置, 应用明码登录

mysql -u root -p '你的明码'

最初,你还须要依照之前的办法增加平安组规定,关上服务器防火墙上的 3306 端口。

配置结束后你就能够在本地近程连贯服务器上的 mysql 了。(倡议 mysql 的明码设置得简单些,平时敞开 3306 端口,这样通过外网就无奈间接连贯 mysql 了,同时还要应用 oss 将 mysql 的数据做好备份以确保安全。之前 mysql 的明码被黑客破解了,所有库表都被删了,惨痛的教训)。

测试

我用的是 Sequelize 包,它是基于 promise 的,反对 es6 语法。除了 mysql,它还能够用于连贯 Postgres、MariaDB、SQLite 和 Microsoft SQL Server。(https://www.npmjs.com/package…

联合开发文档,咱们就能够进行理论开发了。

const Sequelize = require('sequelize');
const config = require('../config');

const logger = require('log4js').getLogger('app');

class MysqlClient {constructor() {if (!MysqlClient.instance) {
      this.client = new Sequelize(config.mysql.database, config.mysql.username, config.mysql.password, {
        host: config.mysql.host,
        port: config.mysql.port,
        dialect: 'mysql',
        pool: {
          max: 5,
          min: 0,
          idle: 10000,
        },
        timezone: '+08:00',
      });

      const client = this.client;
      MysqlClient.instance = client;

      client
      .authenticate()
      .then(() => {logger.info('Connection has been established successfully.');
      })
      .catch(err => {logger.info('Unable to connect to the database:', err);
      });
    }
  }
}

module.exports = new MysqlClient().client;

redis

下载和编译

wget http://download.redis.io/releases/redis-4.0.2.tar.gz
tar xzf redis-4.0.2.tar.gz
cd redis-4.0.2
make

启动服务

后盾启动 redis

cd redis-4.0.2/
src/redis-server &

查问 redis 过程

ps -ef | grep redis

能够看到 redis 曾经启动了

root     19141 19065  0 12:50 pts/1    00:00:03 ./src/redis-server 0.0.0.0:6379
root     19238 19196  0 14:00 pts/0    00:00:00 grep --color=auto redis

完结过程

kill -9 pid

简略测试

启动 redis 客户端

cd redis-4.0.2/
src/redis-cli
127.0.0.1:6379> set test 1
OK
127.0.0.1:6379> get test
"1"

redis 装置胜利了。

配置服务器近程连贯

默认配置只能是本地拜访,咱们批改 redis-4.0.2/redis.conf 配置文件

bind 127.0.0.1

批改为

bind 0.0.0.0 

你须要增加平安组规定,关上服务器防火墙上的 6379 端口。

设置近程连贯明码

默认配置开启了保护模式

protected-mode yes

这时你须要设置明码才能够近程连贯上 redis,明码设置非常简单,只须要在 requirepass 字段上填写你的明码即可

requirepass 你的明码 

配置结束,后盾启动你的 redis 能够了。

./opt/software/redis-4.0.2/src/redis-server /opt/software/redis-4.0.2/redis.conf &

node 客户端连贯

我用的是 redis 包,依据后面你的配置就能够近程连贯服务器上的 redis 了。联合开发文档,就能够进行理论开发了。

const redis = require('redis');
const config = require('../config');

const logger = require('log4js').getLogger('app');

class RedisClient {constructor() {if (!RedisClient.instance) {
      this.client = redis.createClient({
        host: config.redis.host,
        port: config.redis.port,
        password: config.redis.password,
      });

      const client = this.client;
      RedisClient.instance = client;
  
      client.on("error", (err) => {logger.error('redis connect err: %s', err.toString());
      });
      
      client.on("connect", () => {logger.info('redis connect success');
      });
    }
  }
}

module.exports = new RedisClient().client;

短信服务

如果你购买了阿里云的短信服务,就能够通过短信 API 实现验证码、推广短信、告诉短信的发送性能了。

这里以验证码为例,介绍一下短信的发送性能。

疾速学习

进入疾速学习页面 (https://dysms.console.aliyun….

间接点击查看 API Demo

你在左侧输出参数,抉择不同的后端语言,它会主动帮你生成 Demo 代码,并且还能够去 CloudShell 在线调试。

参数阐明

PhoneNumbers 接管短信的手机号码
SignName 签名名称,在控制台国内音讯签名治理一列增加、查看
TemplateCode 模板 ID,在控制台国内音讯模板治理一列增加、查看
TemplateParam 模板变量对应的理论值,留神肯定要是 JSON 格局。

签名能够设置你的网站名、公司名

模板能够抉择验证码、短信告诉、推广短信 (降级为企业后启用),设置你的短信内容,同时反对变量替换,如我的网站的验证码短信模板内容为:

 您的验证码为:${code},该验证码 5 分钟内无效,请勿透露于别人。

TemplateParam 能够设置 code 变量,发送你须要的内容

"TemplateParam": JSON.stringify({"code": 2}),

短信发送客户端

依据 API Demo,咱们写出本人的短信客户端代码

const Core = require('@alicloud/pop-core');
const config = require('../config');

const requestOption = {method: 'POST',};

class SmsClient {constructor() {if (!SmsClient.instance) {
      this.client = new Core({
        accessKeyId: config.sms.accessKeyId,
        accessKeySecret: config.sms.accessKeySecret,
        endpoint: config.sms.endpoint,
        apiVersion: config.sms.apiVersion,
      });
      SmsClient.instance = this.client;
    }
  }

  sendSms(params) {this.client.request('SendSms', params, requestOption).then((result) => {console.log(JSON.stringify(result));
    }, (ex) => {console.log(ex);
    })
  }
}

module.exports = new SmsClient();

编写单元测试

const smsClient = require('../../common/sms-client.js');

describe('smsClient',async function() {it('sendSms', async function() {
    const params = {
      "PhoneNumbers": "手机号码",
      "SignName": "签名",
      "RegionId": "cn-hangzhou",
      "TemplateCode": "模板 ID",
      "TemplateParam": JSON.stringify({"code": 2}),
    }
    smsClient.sendSms(params);
  });
});

执行后,手机上胜利收到了短信。

域名、DNS、nginx

域名

尽管通过 ip 地址能够间接拜访你的网站,然而咱们很少看到网站是通过 ip 地址拜访的,个别网站都会提供域名。域名直观易记,且在用户拜访的域名不扭转的状况下,解析的 ip 地址能够更改。

域名申请能够去万网购买,国家规定了网站须要备案才能够拜访,我在阿里云走的备案流程,在阿里云 APP 填写、上传相应信息即可,以前的流程须要邮寄幕布什么的了,当初只须要在线上操作即可。阿里云的流程走得是比拟快的,最终会提交到管局,管局流程就须要期待一阵子了 (5~20 个工作日)。我的域名从开始备案到备案胜利,流程约走了 2 周。

DNS

域名须要解析到 ip 地址,DNS 做的就是这个工作。它能够将易于治理辨认的域名转换为计算机用于互连通信的数字 IP 地址,从而将用户的拜访路由到相应的网站或应用服务器。

同样,我应用了阿里云的 DNS 解析服务。在云解析 DNS 域名控制台 - 域名解析,点击增加域名。

再增加解析

具体配置

配置实现后拜访域名就会解析到记录值所填写的 ip 地址了。

nginx

尽管域名解析到了 ip 地址 (服务器),然而默认的端口是 80(所以请确保服务器的 80 端口设置了平安组规定,具体能够参考后面文章介绍过的办法)。咱们个别服务监听的端口不是 80 怎么办?其实很简略,咱们只须要简略的配置一下 nginx 转发就能够了。

接下介绍一下在阿里云服务器上安装和应用 nginx。

装置

首先装置 PCRE pcre-devel 和 Zlib

PCRE(Perl Compatible Regular Expressions) 是一个 Perl 库,包含 perl 兼容的正则表达式库。nginx 的 http 模块应用 pcre 来解析正则表达式,所以须要在 linux 上装置 pcre 库,pcre-devel 是应用 pcre 开发的一个二次开发库。nginx 也须要此库。命令:

yum install -y pcre pcre-devel

zlib 库提供了很多种压缩和解压缩的形式,nginx 应用 zlib 对 http 包的内容进行 gzip,所以须要在 Centos 上装置 zlib 库。

yum install -y zlib zlib-devel

装置 GCC 和 OpenSSL

yum install gcc-c++
yum install -y openssl openssl-devel

当初咱们开始装置 nginx,这里我装置的是 1.14.0 版本

wget -c https://nginx.org/download/nginx-1.14.0.tar.gz

解压并进入 nginx 目录

tar -zxvf nginx-1.14.0.tar.gz
cd nginx-1.14.0

应用 nginx 的默认配置

./configure

编译装置

make
make install

查找装置门路:

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# whereis nginx
nginx: /usr/local/nginx

进入 sbin 目录,能够看到有一个可执行文件 nginx,间接./ 执行就 OK 了。

[root@iZ8vbfhrv1vsbp44n9fdtoZ ~]# cd /usr/local/nginx
[root@iZ8vbfhrv1vsbp44n9fdtoZ nginx]# ls
client_body_temp  fastcgi_temp  logs        sbin       uwsgi_temp
conf              html          proxy_temp  scgi_temp
[root@iZ8vbfhrv1vsbp44n9fdtoZ nginx]# cd sbin
[root@iZ8vbfhrv1vsbp44n9fdtoZ sbin]# ls
nginx
[root@iZ8vbfhrv1vsbp44n9fdtoZ sbin]# ./nginx

配置开机自启动

在 rc.local 减少启动代码就能够。减少一行 /usr/local/nginx/sbin/nginx

vi /etc/rc.local

设置执行权限:

chmod 755 rc.local

配置

nginx 配置文件批改

vim /usr/local/nginx/conf/nginx.conf

批改原配置文件的局部内容

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;

    #access_log  logs/host.access.log  main;

    location / {
        root   /opt/nodejs/blog-server/static/blog;
        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   html;}

    # proxy to the blog server
    location /blog {proxy_pass http://0.0.0.0:3000;}
}

这样拜访 80 端口根门路就会申请 index.html 文件,匹配 /blog 门路的申请会被转发到本地服务器的 3000 端口上。

配置结束后,能够执行命令检查一下配置是否有谬误

[root@iZ8vbfhrv1vsbp44n9fdtoZ conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

最初重启一下 nignx 就能够了

/usr/local/nginx/sbin/nginx -s reload

此时你拜访域名,就会依照 nginx 配置申请前后端资源。试试拜访我的网站 (http://www.readingblog.cn)

配置 HTTPS

筹备

  1. 备案过的域名
  2. ssl 证书 (收费的就行)

申请证书

  1. 登录阿里云控制台产 -> 产品与服务 ->SSL 证书
  2. 点击购买证书,证书类型抉择收费型 DV SSL,实现购买
  3. 购买完当前,呈现了 Symantec 免费版 SSL,操作项下按钮点击。
  4. 欠缺材料、提交审核。我这里域名用的是阿里云 DNS 服务,依照提醒勾选证书绑定的域名在阿里云的云解析,系统生成 CSR,直至提交审核。

10 分钟左右,申请的证书就能审核通过。

下载证书

确认已取得证书就能够去证书控制台下载证书了,解压后会失去两个文件

3064445_readingblog.cn.key 3064445_readingblog.cn.pem

不同的服务器类型,证书配置办法也不一样,这里咱们以 nginx 服务器为例做介绍

配置 nginx 的 https

  1. 创立存储证书的目录(任意)
sudo mkdir -p /usr/local/nginx/ssl/key
  1. 上传证书
scp -p 22 /usr/local/nginx/ssl/key/3064445_readingblog.cn.pem root@47.92.166.108:/usr/local/nginx/ssl/key

scp -p 22 /usr/local/nginx/ssl/key/3064445_readingblog.cn.key root@47.92.166.108:/usr/local/nginx/ssl/key

上传完毕后,目录构造如下

[root@iZ8vbfhrv1vsbp44n9fdtoZ key]# pwd
/usr/local/nginx/ssl/key
[root@iZ8vbfhrv1vsbp44n9fdtoZ key]# ls
3064445_readingblog.cn.key  3064445_readingblog.cn.pem
  1. 批改 nginx 配置文件
# HTTPS server
#
server {
    listen       443 ssl;
    server_name  localhost;

    ssl_certificate      /usr/local/nginx/ssl/key/3064445_readingblog.cn.pem;
    ssl_certificate_key  /usr/local/nginx/ssl/key/3064445_readingblog.cn.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
#    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    location / {
        root   /opt/nodejs/blog-server/static/blog;
        index  index.html index.htm;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {root   html;}
    location /blog {proxy_pass http://0.0.0.0:3000;}

}
  1. 重启 nginx
/usr/local/nginx/sbin/nginx -s reload

装置 ngx_http_ssl_module

如果提醒 the “ssl” parameter requires ngx_http_ssl_module,阐明 nginx 还须要装置 ngx_http_ssl_module 模块。

我的 nginx 装置目录为:/usr/local/nginx,源码包在 /usr/nginx-1.14.0
首先进入源码包目录,执行

./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

配置实现后,运行命令 make 命令 (留神此处不能进行 make install,否则就是笼罩装置)

make

替换已装置好的 nginx 包,替换之前先备份:

cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.bak

先进行 nginx 服务:

/usr/local/nginx/sbin/nginx -s stop

将刚刚编译好的 nginx 笼罩掉原有的 nginx

cp ./objs/nginx /usr/local/nginx/sbin/

最初就能够启动 nginx 了

/usr/local/nginx/sbin/nginx

删除备份

rm -rf /usr/local/nginx/sbin/nginx.bak

咱们能够通过命令查看 ssl 模块是否曾经退出胜利

[root@iZ8vbfhrv1vsbp44n9fdtoZ nginx-1.14.0]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.14.0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

配置实现后就能够通过 https 拜访网站了 (https://www.readingblog.cn)

正文完
 0