Pull to refresh

Развёртывание node.js на платформе heroku

Начало


Как гласит википедия:

Heroku — облачная PaaS-платформа, поддерживающая ряд языков программирования.


Чтобы успешно запустить проект на heroku, нам понадобятся базовые знания node.js, а также:
1) Аккаунт на heroku | регистрация
2) необходимо использовать менеджер пакетов NPM

Установка

Итак, приступим. Первое что необходимо сделать — это установить heroku toolbelt. Так же у вас должен быть устанолен git

После всех манипуляций у вас должен установится клиент heroku. После этого открываем терминал:
$ heroku login

Enter your Heroku credentials.
Email: adam@example.com
Password:
Could not find an existing public key.
Would you like to generate one? [Yn]
Generating new SSH public key.
Uploading ssh public key /Users/adam/.ssh/id_rsa.pub


А теперь начинается самое интересное, мы загрузим код в heroku
Создадим файл index.js
var express = require("express");
var app = express();
app.use(express.logger());

app.get('/', function(request, response) {
  response.send('Hello World!');
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});


Следующий шаг — необходимо создать файл/отредактировать файл package.json
В нашем случае, мы используем только модул express, поэтому добавим его в зависимости

{
  "name": "node-example",
  "version": "0.0.1",
  "dependencies": {
    "express": "3.1.x"
  },
  "engines": {
    "node": "0.10.x",
    "npm": "1.3.x"
  }
}


В нём мы так же указываем какую версию npm и node.js мы хотим использовать
Узнать версии, устновленные в вашей системе можно просто:
$ npm -v
1.3.8

$ node -v
v0.10.17


Мы почти заставили работать наше приложение, осталось сделать совсе чуть чуть
Создадим файл Procfile
web: node index.js

он нужен для того, чтобы heroku знал что надо запускать

Итак, мы подготовили все для того, чтобы наконец вкусить плоды нашего труда
создаем локалный репозиторий на рабочй машине
Создание репозитория

$ git init
$ git add .
$ git commit -m "init"


и выкатываем всё на heroku

$ heroku create
Creating sharp-rain-871... done, stack is cedar
http://sharp-rain-871.herokuapp.com/ | git@heroku.com:sharp-rain-871.git
Git remote heroku added


Вуаля, последний штрих

$ git init
$ git add .
$ git commit -m "init"


создаем приложение

$ heroku create
Creating sharp-rain-871... done, stack is cedar
http://sharp-rain-871.herokuapp.com/ | git@heroku.com:sharp-rain-871.git
Git remote heroku added


и выкатываем всё на heroku

$ git push heroku master
Counting objects: 343, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (224/224), done.
Writing objects: 100% (250/250), 238.01 KiB, done.
Total 250 (delta 63), reused 0 (delta 0)

-----> Node.js app detected
-----> Resolving engine versions
       Using Node.js version: 0.10.3
       Using npm version: 1.2.18
-----> Fetching Node.js binaries
-----> Vendoring node into slug
-----> Installing dependencies with npm
       ....
       Dependencies installed
-----> Building runtime environment
-----> Discovering process types
       Procfile declares types -> web

-----> Compiled slug size: 4.1MB
-----> Launching... done, v9
       http://sharp-rain-871.herokuapp.com deployed to Heroku

To git@heroku.com:sharp-rain-871.git
 * [new branch]      master -> master


Итог


Теперь наше приложение, написанное на node.js, работает в облаке heroku и доступно по адресу
sharp-rain-871.herokuapp.com

При написании статьи была использована документация heroku.com
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.