본문 바로가기
Javascript

Heroku에 node.js 서버 배포하기

by 안자바먹지 2021. 3. 8.
728x90

Heroku

 

Heroku (헤로쿠)는 자신이 개발한 어플리케이션을 웹 상에 서비스하기 위한 서버를 제공해 준다.

자신이 개발한 어플리케이션을 Heroku에 배포해보자.

 

 

회원가입

 

dashboard.heroku.com/

 

Heroku

 

dashboard.heroku.com

 

필요 정보 입력

 

로그인을 이메일로 하기 때문에 자주 사용하고 있는 이메일을 사용한다.

 

1. 빈칸 채우고 CREATE FREE ACCOUNT 를 클릭하여 회원가입 완료

2. 작성한 이메일로 인증 메일이 오면 인증

3. 패스워드 설정

4. 완료

 

 

app 생성

 

 

Create new app 버튼을 눌러 새로운 app을 생성한다.

 

App name은 추후 자신의 서비스 주소가 되기 때문에 중복되지 않게 잘 찾아서 작성한다.

 

 

 

 

Heroku CLI 설치

 

App name을 정하고 app을 만들었다면 아래와 같은 화면을 볼 수 있다.

 

 

먼저 표시한 부분을 클릭하여 Heroku CLI를 설치한다.

 

 

자신의 운영체제에 맞게 다운로드 받고 인스톨 한다.

 

 

인스톨 후 heroku -v 으로 잘 설치가 되었는지 확인한다.

 

 

 

Heroku 세팅

 

그 다음은 아래에 나와있는것과 같이 진행 하면 된다.

heroku login 은 여러분들이 배포할 어플리케이션의 server 디렉토리에서 진행하면 된다.

 

 

heroku login으로 로그인을 하였으면 아래와 같은 화면이 떴으면 그 다음 프로세스를 계속 진행하면 된다.

 

 

 

필자는 이미 git과 연동하여 만들어놓은 어플리케이션이 있기 때문에 바로

heroku git:remote 명령어를 실행하였고, remote에 heroku가 추가된 것을 확인할 수 있다.

 

 

 

 

어플리케이션 소스 수정

 

// server/index.js

app.get('/', (req, res) => {
  res.send('welcome to my memories :)')
})

 

// .env
// PORT = 5000
CONNECTION_URL = '몽고디비 URL'

 

// client/api/index.js

import axios from 'axios'

const url = 'https://"설정한 주소".herokuapp.com/posts'

export const fetchPosts = () => axios.get(url)
export const createPost = (newPost) => axios.post(url, newPost)
export const updatePost = (id, updatedPost) => {
  return axios.patch(`${url}/${id}`, updatedPost)
}
export const deletePost = (id) => axios.delete(`${url}/${id}`)
export const likePost = (id) => axios.patch(`${url}/${id}/likePost`)

 

index.js에 기본경로를 따로 지정해준다.

PORT는 heroku에서 지정하고 있는 포트를 사용하기 때문에 지워준다.

클라이언트 부분에서 api 호출하고 있는 url도 자신이 사용하는 heroku 주소로 변경해 준다.

 

🔔주의사항🔔

.env 파일에서 관리하고 있는 변수들은 github에 올라가면 안되는 정보들이 있기 때문에 보통 .gitignore에서 관리되고 있다. 하지만 heroku는 .env 파일의 정보가 있어야 한다. 그럴 경우엔 해당 App의 settings에서 Config Vars에 추가해 주면 된다.

 

 

 

 

 

 

Procfile 생성

Procfile은 heroku에게 프로젝트를 실행하기 위한 명령어의 순서를 알려주는 용도이다.

server 경로에 Procfile을 생성한다. 

 

// Procfile

web: npm run start

 

 

배포시작

 

$ git add .

$ git commit -am "make it better"

$ git push heroku master

 

명령어로 배포를 시작하면 되는데 

필자의 경우 아래와 같은 오류가 발생하였다.

 

그 이유는 먼저 기본 buildpack을 감지하지 못하여 생긴 오류였고, 이 오류는 

간단하게 heroku buildpacks:set heroku/nodejs 로 해결했다.

 

remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Building on the Heroku-20 stack
remote:  !     No default language could be detected for this app.
remote:                         HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
remote:                         See https://devcenter.heroku.com/articles/buildpacks
remote:
remote:  !     Push failed
remote:  !
remote:  ! ## Warning - The same version of this code has already been built: ca016f2ea1a086257253a435897f15a727ac033b
remote:  !
remote:  ! We have detected that you have triggered a build from source code with version ca016f2ea1a086257253a435897f15a727ac033b
remote:  ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
remote:  !
remote:  ! If you are developing on a branch and deploying via git you must run:
remote:  !
remote:  !     git push heroku <branchname>:main
remote:  !
remote:  ! This article goes into details on the behavior:
remote:  !   https://devcenter.heroku.com/articles/duplicate-build-version
remote:
remote: Verifying deploy...
remote:
remote: !       Push rejected to ab-my-memories.
remote:

 

하지만 문제는 그 다음이었는데

현재 배포하고자 하는 프로젝트는 이렇게 client와 server가 하나의 프로젝트 안에

각각 분리되어 있다.

 

 

이 상태에서 다시 $ git push heroku master 했으나 오류가 발생하였고,

그 이유는 root 디렉토리에 package.json이 없어서 그런것이었다.

 

그래서 따로 server 부분을 별도의 레파지토리를 만들어 분리하려고 했으나, 한번에 관리 하고 싶었고

이것저것 찾아보니 git subtree를 사용하면 분리하지 않을 수 있었다.

 

해당 내용은

stackoverflow.com/questions/5977234/how-can-i-push-a-part-of-my-git-repo-to-heroku

 

How can I push a part of my git repo to Heroku?

I have a multi-module app that is already on Github. It is comprised of two modules, one of them an Android app and the other a Rails based Web app. So my project's directory structure is in the fo...

stackoverflow.com

stackoverflow.com/questions/7539382/how-can-i-deploy-push-only-a-subdirectory-of-my-git-repo-to-heroku

 

How can I deploy/push only a subdirectory of my git repo to Heroku?

I have a project that uses Serve and is version controlled using Git. Serve creates an output folder with static files that I want to deploy to Heroku. I don't want to deploy the Serve project its...

stackoverflow.com

이곳을 참조하였다.

 

계속해서 $ git subtree push --prefix server heroku master 명령어를 통해 배포를 성공하였다.

728x90

'Javascript' 카테고리의 다른 글

헷갈리는 Javascript Compare 함수  (1) 2021.03.29
netlify에 client 어플리케이션 배포하기  (0) 2021.03.08
고차함수 / 커링 / 부분적용함수  (0) 2020.12.29
async / await  (0) 2020.11.27
프로미스  (0) 2020.11.27

댓글