# 9. Развертывание приложения в Heroku

### 1. Настройка Heroku и подключения к БД

Создадим аккаунт на сервисе Heroku

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudR7QE_Zp6e3gEktC9%2Fimage.png?alt=media\&token=9a7ad801-cb64-47a2-8a23-aa8b9e5df0af)

Зайдем в аккаунт и создадим новое приложение (new app)

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudRiOfAw28M3vtrSXz%2Fimage.png?alt=media\&token=734c43c6-6eb7-4c68-8392-f3461d37232e)

Зайдем в раздел Resources, в пункте Add-ons добавим Heroku Postgres

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudSM1CurPymHcQOu4W%2Fimage.png?alt=media\&token=7ae75e19-aeaf-4320-a322-9fbc1dffeddb)

Перейдем в настройки базы данных

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudT6umQsKykwqG0lp1%2Fimage.png?alt=media\&token=2e69bae9-1fcb-48b5-a034-ac2b60b3fb29)

На страничке адд-она перейдем в раздел Settings и выберем View Credentials

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudTTy9ne4g4-x2_mXc%2Fimage.png?alt=media\&token=0aed9f63-9394-4756-b29f-144a39aa6151)

Таким образом, мы получим credentials для подключения к базе.

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudQfcJM8LrVYNuRx9B%2F-LudToePl2JPr33Lv7Kb%2Fimage.png?alt=media\&token=eebddca6-1b79-4be0-97b1-374b634290cc)

Перейдем в application.yml и укажем настройки для БД на heroku

{% code title="application.yml" %}

```yaml
spring:
  jpa:
    database: POSTGRESQL
    show-sql: true
    hibernate:
      ddl-auto: create-drop
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
  datasource:
    platform: postgres
    url: jdbc:postgresql://ec2-176-34-183-20.eu-west-1.compute.amazonaws.com:5432/d60ukqmkatvcpg
    username: xvlmxbawwxafdu
    password: a1439fbcffbfdd6ad208df91670a37c73d8ed12d18cd6de91c1485c5841774b9
    driverClassName: org.postgresql.Driver
```

{% endcode %}

{% hint style="info" %}
После указания настроек, можете сразу запустить приложение, чтобы убедиться, что вы правильно указали настройки для подключения БД.
{% endhint %}

### 2. Установка git и heroku

Заходим на сайт <https://git-scm.com/>, скачиваем последнюю версию установщик и устанавливаем Git.

Заходим в командную строку и настраиваем имя и почту разработчика

```yaml
Microsoft Windows [Version 10.0.18362.476]
(c) Корпорация Майкрософт (Microsoft Corporation), 2019. Все права защищены.

C:\Users\nickg>git config --global user.name "Mykola Hodovychenko"

C:\Users\nickg>git config --global user.email hodovychenko@opu.ua

C:\Users\nickg>git config --list
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
core.autocrlf=true
core.fscache=true
core.symlinks=false
core.editor="C:\\Program Files\\Notepad++\\notepad++.exe" -multiInst -notabbar -nosession -noPlugin
credential.helper=manager
user.name=Mykola Hodovychenko
user.email=hodovychenko@opu.ua
gui.recentrepo=E:/spring/testproject3

C:\Users\nickg>
```

Возвращаемся в Heroku, скачиваем и настраиваем Heroku CLI

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-LudgoLYT0zOwlg34p8o%2F-LudguL-fN4vz8L0i6CF%2Fimage.png?alt=media\&token=1bfa725c-70a3-4fe8-bf7c-a11aee77f805)

Заходим в командую строку и логинимся на heroku с помощью команды `heroku login`

```yaml
C:\Users\nickg>heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/browser/630e1a02-f90e-4217-8170-cd71d7fc700e
Logging in... done
Logged in as hodovychenko@opu.ua
```

Переходим в директорию проекта, после чего инициализируем git-репозиторий с помощью команды `git init`

```yaml
C:\Users\nickg>cd d:\springdemo\ejo

d:\springdemo\ejo>git init
Initialized empty Git repository in d:/springdemo/ejo/.git/
```

Далее устанавливаем удаленный репозиторий

```yaml
d:\springdemo\ejo>heroku git:remote -a opnu-ej
set git remote heroku to https://git.heroku.com/opnu-ej.git
```

Начинаем отслеживать файлы проекта с помощью команды `git add .`, после чего делаем коммит с помощью команды `git commit -am "initial commit"`.

```yaml
d:\springdemo\ejo>git add .
warning: LF will be replaced by CRLF in .gitignore.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in .mvn/wrapper/MavenWrapperDownloader.java.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in .mvn/wrapper/maven-wrapper.properties.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in mvnw.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in mvnw.cmd.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in pom.xml.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in src/main/java/com/example/ejo/EjoApplication.java.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in src/test/java/com/example/ejo/EjoApplicationTests.java.
The file will have its original line endings in your working directory

d:\springdemo\ejo>git commit -am "initial commit"
[master (root-commit) 162bc53] initial commit
 16 files changed, 886 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 .mvn/wrapper/MavenWrapperDownloader.java
 create mode 100644 .mvn/wrapper/maven-wrapper.jar
 create mode 100644 .mvn/wrapper/maven-wrapper.properties
 create mode 100644 mvnw
 create mode 100644 mvnw.cmd
 create mode 100644 pom.xml
 create mode 100644 src/main/java/com/example/ejo/Controller.java
 create mode 100644 src/main/java/com/example/ejo/EjoApplication.java
 create mode 100644 src/main/java/com/example/ejo/Group.java
 create mode 100644 src/main/java/com/example/ejo/GroupRepository.java
 create mode 100644 src/main/java/com/example/ejo/Service.java
 create mode 100644 src/main/java/com/example/ejo/Student.java
 create mode 100644 src/main/java/com/example/ejo/StudentRepository.java
 create mode 100644 src/main/resources/application.yml
 create mode 100644 src/test/java/com/example/ejo/EjoApplicationTests.java
```

Теперь можно пушить проект на удаленный репозиторий с помощью команды `git push heroku master`.

```yaml
d:\springdemo\ejo>git push heroku master
Enumerating objects: 32, done.
Counting objects: 100% (32/32), done.
Delta compression using up to 6 threads
Compressing objects: 100% (23/23), done.
Writing objects: 100% (32/32), 54.39 KiB | 9.06 MiB/s, done.
Total 32 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Java app detected
remote: -----> Installing JDK 1.8... done
remote: -----> Executing: ./mvnw -DskipTests clean dependency:list install
remote:        [INFO] Scanning for projects...

...

remote:        [INFO] Replacing main artifact with repackaged archive
remote:        [INFO]
remote:        [INFO] --- maven-install-plugin:2.5.2:install (default-install) @ ejo ---
remote:        [INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.4/maven-shared-utils-0.4.pom
remote:        [INFO] Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.4/maven-shared-utils-0.4.pom (4.0 kB at 450 kB/s)
remote:        [INFO] Downloading from central: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar
remote:        [INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.4/maven-shared-utils-0.4.jar
remote:        [INFO] Downloaded from central: https://repo.maven.apache.org/maven2/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar (38 kB at 1.1 MB/s)
remote:        [INFO] Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.15/plexus-utils-3.0.15.jar
remote:        [INFO] Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-utils/0.4/maven-shared-utils-0.4.jar (155 kB at 2.0 MB/s)
remote:        [INFO] Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/3.0.15/plexus-utils-3.0.15.jar (239 kB at 3.0 MB/s)
remote:        [INFO] Installing /tmp/build_bee447e74484e663663b1d166f8e9456/target/ejo-0.0.1-SNAPSHOT.jar to /app/tmp/cache/.m2/repository/com/example/ejo/0.0.1-SNAPSHOT/ejo-0.0.1-SNAPSHOT.jar
remote:        [INFO] Installing /tmp/build_bee447e74484e663663b1d166f8e9456/pom.xml to /app/tmp/cache/.m2/repository/com/example/ejo/0.0.1-SNAPSHOT/ejo-0.0.1-SNAPSHOT.pom
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] BUILD SUCCESS
remote:        [INFO] ------------------------------------------------------------------------
remote:        [INFO] Total time:  20.474 s
remote:        [INFO] Finished at: 2019-11-26T21:46:52Z
remote:        [INFO] ------------------------------------------------------------------------
remote: -----> Discovering process types
remote:        Procfile declares types     -> (none)
remote:        Default types for buildpack -> web
remote:
remote: -----> Compressing...
remote:        Done: 84.1M
remote: -----> Launching...
remote:        Released v5
remote:        https://opnu-ej.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/opnu-ej.git
 * [new branch]      master -> master

d:\springdemo\ejo>
```

Как видим, мы успешно развернули проект на Heroku. Проверим работу веб-сервиса. Перейдем в браузер и укажем адрес <https://opnu-ej.herokuapp.com/>

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-Ludic2ZDLmiGL2L44_2%2F-Ludj_7kiyYh8cAfcTcK%2Fimage.png?alt=media\&token=0d05154a-9fad-4270-8397-2e417e864e1b)

Теперь попробуем осуществить REST-запросы к серверу. Добавим группу, добавим студента, получим список групп.

Добавляем группу

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-Ludic2ZDLmiGL2L44_2%2F-LudjsgOCnDNkAPNMpai%2Fimage.png?alt=media\&token=7eed02e8-0356-4755-b65d-b69e1fd72498)

Добавляем студента

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-Ludic2ZDLmiGL2L44_2%2F-Ludk35F_mKcVREBBe70%2Fimage.png?alt=media\&token=45594f5c-34c5-48e3-b8d3-d22ab9e54e75)

Получаем список групп

![](https://1377473627-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LnhxGhlv6e_zwoZYywB%2F-M25NnFIv5H4pZSLe1U9%2F-M25TolBVobLX8s_egjd%2Fimage.png?alt=media\&token=f010a7d6-8a18-4afd-a638-af8ccac6af07)
