尝试使用了下Heroku, 在上面部署 Node 程序仍是很方便的, 主要优点在于它的网络能够访问到外网, 具体应用都懂得这里记录下如何在 Heroku 上建立、开发、部署 Node node
官方的文档在这里git
其他的访问 下载地址web
使用Yeoman
和generator-express
来快速建立一个 Express 应用shell
// 安装 yeoman npm install -g yo // 安装 generator-express npm install -g generator-express // 新建项目文件夹 mkdir heroku-express cd heroku-express git init // 建立项目 yo express // 提交代码 git add . git commit -m "Init project"
测试一下刚刚建立的项目express
// 启动 Express npm start
访问 http://localhost:3000/ 查看 Express 是否成功启动npm
进入咱们刚刚新建的项目, 运行 create
指令建立项目json
heroku create [your_app_name]
运行完成后, Heroku 会在咱们的项目上新建一个git
的远程分支, 同时会为项目建立一个域名供咱们访问windows
这里是个人运行结果bash
部署以前咱们须要建立一个相似启动脚本的文件 Procfile
服务器
// Profile web: node ./bin/www
这个文件告诉 Heroku
须要建立一个web 容器, 同时执行 node ./bin/www
来启动程序
咱们的项目只须要这样就能够了, 更多的详细信息在这里 Process Types and the Procfile
而后将刚刚的改动提交, 同时推送的 Heroku
git add . git ci -m "Add procfile" git push heroku master
当你将代码推送到 Heroku 的 master 分支上时, 它就会根据package.json
中的内容安装所须要的依赖, 而后执行 Procfile
中的内容, 这就完成的程序的部署
这里是个人部署结果
而后你在访问刚刚 Heroku 给的网址, 就能够看到程序已经运行
经过package.json
定义程序依赖
{ "name": "heroku-express", "version": "0.0.1", ... "dependencies": { "express": "^4.13.3", "serve-favicon": "^2.3.0", "morgan": "^1.6.1", "cookie-parser": "^1.3.3", "body-parser": "^1.13.3", "swig": "^1.4.2" }, ... "engines": { "node": "^8.3.0" } }
dependencies 字段定义程序依赖
engines 字段定义须要的 Node 版本
定义运行变量
本地运行变量
本地使用 .env
文件来定义变量, 格式以下
NAME=VALUE
使用 heroku local web
来启动本地开发服务器, 同时会将变量信息注入到process.env
中
容器的运行变量须要经过 heroku config:set NAME=VALUE
来设置
使用 heroku config
来查看变量
详细信息 Configuration and Config Vars
查看运行日志
heroku logs --tail
在容器中运行命令 heroku run command
heroku run node
进入Node 的 REPLheroku run bash
进去容器运行bashHeroku 的免费版本每一个月提供了 550 小时的使用时间, 当咱们的程序半个小时内没有访问流量时就会被休眠掉, 在下次被访问的时候激活
因此长时间没有访问的应用, 在第一次访问会很慢, 不过也就够用了
我也将这篇文章部署在这个应用上, https://lleohao-heroku-expres...