공식적으로 온라인 사이트가 있습니다!!
코딩 부트캠프의 일환으로 저는 이미 몇 개의 앱과 사이트를 구축했지만 마지막 단계를 수행하고 실제로 인터넷에 내 사이트를 배포하는 방법을 배울 때가 되었다고 결정했습니다. 그것이 들리는 것만큼 쉽지는 않다는 것이 밝혀졌고(충격적이지만, 저도 압니다) 최종 결과에 도달하기 위해 많은 연구와 기존 기사 및 문서의 일부를 결합해야 했습니다. 그래서 저는 누군가(에헴… 나)가 문제를 겪고 단계별 가이드를 원하는 자신을 발견하는 경우를 대비하여 제가 이 작업을 수행한 방법을 문서화할 것이라고 생각했습니다.
면책 조항으로서, 이 프로세스의 세부 사항은 많은 요인에 따라 크게 달라집니다. 저는 Ubuntu OS와 함께 Linux용 Windows Subsystem을 실행하는 Windows PC를 사용합니다. 이 사이트의 백엔드는 Puma v3 서버를 실행하는 Ruby-on-Rails v5로 구축되었으며 프런트엔드는 HTML, CSS 및 바닐라를 사용하여 구축되었습니다. 자바스크립트. 기술 조합이 다른 경우 지금까지만 얻을 수 있습니다. 또한 이번이 첫 번째 배포이므로 이를 수행하는 더 좋은 방법이 있다고 확신하며 의견을 듣고 싶습니다. 댓글에서 배운 모범 사례를 자유롭게 던지십시오.
목차
Step 1: Split Your Code
Step 2: Choose Your Platform(s)
Step 3: Download Heroku’s CLI
Step 4: Use Heroku CLI to Create App
Step 5: Create the Procfile
Step 6: Convert Your SQLite3 Database
Step 7: Push to Heroku
Step 8: Add Environment Variables
Step 9: Push Database Migrations to Heroku
Step 10: Link Front-End Code With Live API URL
Step 11: Deploy Your Front-End
Step 12: Enable CORS
Step 13: One Final Gotcha
1단계 - 코드 분할
It’s easy to think of a website as a single entity, but they are actually two separate pieces - the front-end site and the back-end API - that will need to be deployed separately. There are also a lot of different platform options, which may be optimized toward either front-end or back-end apps, so you may want to deploy each side to a separate platform. Due to this, you'll need to split your front-end code to a separate repository from your back-end.
Naturally, there are a lot of ways to do this, but the way that I handled it was to have 3 git tracks: back-end (API), front-end, and combined. I like this approach because on the one hand, it keeps everything contained in one repository for reference (combined), yet at the same time, I can keep separate front & back end repositories for the actual deployment.
Firstly, make sure the Combined repo is fully updated and pushed to GitHub (or whatever version control remote that you use). When referring someone to your GitHub, this will be the link you will send since it will have everything, front and back, all contained in one place.
Next, create a new GitHub Repository for your back-end stuff. I appended mine with "-api" so I could keep track easier. Once that’s created you can ‘cd’ into your local back-end directory and create a brand new git file with the same name using ‘git init’. Then push it into your newly created Remote Repository. Now you have your back-end git file ready to deploy and saved to GitHub.
Then finally, repeat the previous step for your front-end stuff. I appended mine with “-frontend” to keep it separate from the combined repository.
back to top
2단계 - 플랫폼 선택
There are a lot of ways to go with this. Heroku is easily the most common platform that my peers were using for their back-end, and the starting plan is free, so I decided to sign up and use it for my first site. For the front-end, GitHub can actually host your site directly from the GitHub Repository with GitHub Pages (this is why you need to separate the two repositories). This seemed like it would be the most straightforward option, so that’s the route I took.
문서가 진행되는 한 GitHub Pages 문서는 이보다 더 간단할 수 없습니다. 몇 가지 옵션을 전환하면 지침이 출력됩니다. Heroku는 다른 이야기였습니다. 배포 방법에 영향을 미치는 요소가 너무 많아서 해당 문서가 다소 압도적이라는 것을 알았습니다. 즉, 매우 포괄적인 것으로 보이며 가능한 한 간단하고 단계별로 유지하기 위해 최선을 다합니다. 어느 시점에서 막히거나 나처럼 WSL을 사용하는 경우 일반적으로 Windows가 아닌 Linux 지침을 따를 것이라는 점을 기억하십시오.
back to top
3단계 - Heroku CLI 다운로드
If you start by diving into Heroku’s “show next steps” instructions like I did, you will now be instructed to create a new App and add it to a pipeline, and then select a bunch of configurations. I’m sure once I get a better feel for deployment this will all be very useful, but for my first time, I was feeling lost. Luckily, there are a LOT of blog posts and help articles about how to deploy, and I noticed that many of them only mentioned using Heroku CLI during this whole process.
So I deleted everything I had done on Heroku up to this point and went ahead and downloaded the CLI. Unfortunately, this was less straightforward than I had expected. The instructions on Heroku didn’t work because I am using WSL which doesn’t support Snap… Luckily for me, Thomas Wright had had the same issue and wrote an about how to download the CLI with WSL, otherwise this would have been a real ordeal. But all you need to do is run curl https://cli-assets.heroku.com/install.sh | sh
on your Ubuntu terminal and you’ll be good to go with the CLI.
back to top
4단계 - Heroku CLI를 사용하여 앱 만들기
From the root of your back-end directory (not of the whole app) you will use the CLI to run commands that are very similar to the git workflow:
- Create an empty Heroku app with your app name (I kept the “-api” for clarity):
heroku create -a <app-name>-api
** This command will also create a remote repository linked to whatever you called the command from – this is why you call it from the root of your back-end
- Run
git remote -v
to check that there is indeed a Heroku remote. It should look like this if all went well:
back to top
5단계 - 프로필 생성
Heroku uses a Procfile on the root of the back-end directory to execute startup commands, like starting up your server. The “Rails New” generator sets up Puma in a way that works right out of the box, you can view the details in your ./config/puma.rb. The only thing we need to with the procfile then, is to create it and add a web-process that starts Puma according to the specifications in the config file. This does the trick: web: bundle exec puma -C config/puma.rb
.
back to top
6단계 - SQLite3 데이터베이스 변환
Rails is set up to use SQLite3 for the database by default. This won’t work on Heroku, so we need to change it. I changed it to Postgres as recommended in the Heroku documentation. I thought I’d have to rebuild my database migrations and do a lot of extra work to do this, but it was actually super simple. Just go into your gemfile and replace “gem ‘sqlite3’” with “gem ‘pg’” and run bundle install. Hopefully you’ll get a new ./config/database.yml file that is adapted to Postgres, but I did not. Luckily all I had to do was change the adapter to “postgresql” and add an encoding line set to Unicode and I was good to go.
default: &default
adapter: postgresql
encoding: unicode
The only gotcha that I ran into was that Postgres seems to be a little bit more strict with its migration order. Evidently I had created a table that references another table prior to its creation. I just had to switch the order of the migrations around and everything worked fine. From now on though, I’ll probably just build my Rails APIs using Postgres to skip this whole issue.
back to top
7단계 - Heroku로 푸시
Now, you’re finally done prepping your code and you can push to Heroku. Just use the CLI to add git add .
, commit git commit -m “_commit message_”
, and push your code to Heroku git push heroku master
and you’re done! You should only push to Heroku master branch, non-master branches won’t deploy.
back to top
8단계 - 환경 변수 추가
I had some features in my site that were dependent on secret variables - JSON Web Token Secret for authentication, and a 3rd party API Key. If you use the dotenv gem, these would be in your .env file. They need to be added to Heroku by going into the app’s settings and scrolling to the Config Vars section and adding the Keys and Values. Took me a little bit and some heavy debugging to figure that one out.
back to top
9단계 - 데이터베이스 마이그레이션을 Heroku로 푸시
Once the App is all set up and fully pushed to Heroku, you can push your database migrations to set up your production database using the Heroku CLI: “heroku run rake db:migrate”. And now, your api should be fully live and working!
back to top
이제 어려운 부분은 끝났습니다 - 휴!
10단계 - 라이브 API URL과 프런트 엔드 코드 연결
Your front-end likely connects to your api using fetch calls. The URL in all of these calls needs to be changed from your localhost address to the live URL for your API. Once you do this, the site will be pulling from your production database.
back to top
11단계 - 프런트 엔드 배포
Deploying your front-end code is super simple with GitHub Pages. Just go into your front-end repository (remember, not the combined one), go to Settings, and scroll down to the GitHub Pages Section. Here, you simply select the branch that you want to deploy and click Save and you’re done.
back to top
12단계 - CORS 활성화
Now that you have a live front-end site (woohoo!) you just need your back-end API to allow it access. You probably set up CORS during development, but you have it pointed at the localhost URL. This will need to change to the new, live front-end URL in your ./config/initializers/cors.rb file. If you know this address ahead of time, you can set up CORS as part of your back-end code prep (Step 5 & 6).
back to top
거기. 이제 인터넷에 완벽하게 작동하는 웹사이트가 있어야 합니다!! 원하는 간식이나 음료를 들고 컴퓨터를 치우고 다른 사람의 장치에서 새 사이트를 사용하여 축하할 시간입니다. 또는 더 나은 방법은 시청하고 휴식을 취하는 동안 사이트에서 플레이하도록 하는 것입니다.
13단계? - 하나의 마지막 잡았다
For me, when I tested my site the authentication failed, although it was working just fine in development. I learned 2 things through debugging this issue:
- It’s much harder to debug a live App. The logs are much less detailed and you can’t throw in a
binding.pry
to stop the code. So use custom logging generously puts ‘…’
to help you see where things are breaking. You can run heroku logs -t
from your terminal to view your logs on the terminal, or you can go to the App in the Heroku website and view logs from the “More” button.
- Ruby implicitly returns the last line processed in a method, but this might not be a safe assumption to make. Somehow, a method in my code was not returning anything because I had a missing return. It worked locally, but not with Heroku. If you’re site seems to be broken for no reason – check your returns.
추신 – 나는 이것이 현재 세계에서 가장 예쁜 사이트가 아니라는 것을 압니다. 그것은 초기 프로젝트였으며 작업할 시간을 찾는 대로 개선될 것입니다.
back to top
Reference
이 문제에 관하여(공식적으로 온라인 사이트가 있습니다!!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/dhintz89/i-officially-have-a-site-online-5ep4
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
curl https://cli-assets.heroku.com/install.sh | sh
on your Ubuntu terminal and you’ll be good to go with the CLI.heroku create -a <app-name>-api
** This command will also create a remote repository linked to whatever you called the command from – this is why you call it from the root of your back-endgit remote -v
to check that there is indeed a Heroku remote. It should look like this if all went well:
web: bundle exec puma -C config/puma.rb
.default: &default
adapter: postgresql
encoding: unicode
git add .
, commit git commit -m “_commit message_”
, and push your code to Heroku git push heroku master
and you’re done! You should only push to Heroku master branch, non-master branches won’t deploy.binding.pry
to stop the code. So use custom logging generously puts ‘…’
to help you see where things are breaking. You can run heroku logs -t
from your terminal to view your logs on the terminal, or you can go to the App in the Heroku website and view logs from the “More” button.Reference
이 문제에 관하여(공식적으로 온라인 사이트가 있습니다!!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dhintz89/i-officially-have-a-site-online-5ep4텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)