Contents
  1. 1. 启用 EPEL
  2. 2. 安装 nodejs, npm
  3. 3. 安装 forever 守护进程
  4. 4. 安装并运行 redis 服务(可安装到另一台服务器上)
  5. 5. 上传代码到服务器上
  6. 6. 运行服务

本文介绍 socket.io 在CentOS 7上的安装过程,需要启用EPEL仓库

启用 EPEL

yum install -y epel-release

安装 nodejs, npm

yum install -y nodejs npm
node --version # 确认 nodejs 是否安装成功

安装 forever 守护进程

npm install -g forever

安装并运行 redis 服务(可安装到另一台服务器上)

yum install -y redis # 安装 redis
systemctl enable redis # 启用 redis 服务
systemctl start redis # 运行 redis 服务

上传代码到服务器上

scp app.tar.bz2 root@192.168.56.101:/root/ # 192.168.56.101 需要改成实际的服务器IP地址
tar xvf app.tar.bz2 # 解压代码
cd app
npm install # 安装软件包依赖
如果 redis 是安装到另外的服务器,则需要更改 index.js 中的 127.0.0.1 为 redis 服务器的 IP 地址

运行服务

为保证系统重启后自动运行服务,需要配置systemd service:
cd /usr/lib/systemd/system
建立 service 文件:
vim napp.service
写入如下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[Unit]
Description=socket.io server
After=network.target redis.service
[Service]
Type=forking
PIDFile=/run/napp.pid
ExecStart=/usr/bin/forever start --pidFile /run/napp.pid /var/nodejs/napp/index.js
ExecReload=/usr/bin/forever restart --pidFile /run/napp.pid /var/nodejs/napp/index.js
ExecStop=/usr/bin/forever stop --pidFile /run/napp.pid /var/nodejs/napp/index.js
PrivateTmp=true
[Install]
WantedBy=multi-user.target

systemctl enable napp.service # 启用服务
systemctl start napp.service # 运行服务
ss -atln | fgrep 3000
结果中如果有如下内容,则说明运行成功:
LISTEN 0 128 *:3000 *:*
否则说明运行失败,需要执行systemctl status napp.service,以查看运行日志

当客户端的连接数非常多时,可改用 nginx做负载均衡服务器,详细的配置方式见 http://socket.io/docs/using-multiple-nodes/

Contents
  1. 1. 启用 EPEL
  2. 2. 安装 nodejs, npm
  3. 3. 安装 forever 守护进程
  4. 4. 安装并运行 redis 服务(可安装到另一台服务器上)
  5. 5. 上传代码到服务器上
  6. 6. 运行服务