일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- docker
- node.js
- 비트코인
- Cookie
- PL/SQL
- 블록체인
- 웹게임
- 알고리즘
- websocket
- Servlet
- autowired
- CSS
- tiles.xml
- JSP
- AWS
- EC2
- Ajax
- SQL
- express
- HTML
- RDS
- phaser
- 웹소켓
- 배포
- JavaScript
- 도커
- jQuery
- model1
- 암호화
- Spring
- Today
- Total
記錄
mina 를 활용한 배포 본문
회사에서 처음으로 mina를 활용하여 배포를 해보았다. 하면서 막힌 것이 조금 많았고 기계적으로는 가능한데 무슨 내용인지도 모르고 하는 것은 의미가 없어서 이것저것 뒤져서 총 정리를 해보았다.
코드를 풀기 전 간략하게 설명하자면 mina라는 gem은 코드의 배포를 수월하게 해주는 툴이다. mina를 이용해서 mina가 요구하는 설정대로 내용을 채워준다음 시동어로 명령하면 알아서 서버에 들어가서 쉘스크립트를 순차적으로 실행해서 모든 것을 해준다. 더 자세히 풀어서 설명하자면 서버 컴퓨터에 직접 ssh를 통해 접속하여 깃으로부터 클론하고, 이것저것 공유 폴더 설정하고 관련한 서버 설정하고 루비 설정하고 등등 할 일을 mina를 통해서 로컬에서 한 파일 내에 다 설정하여 순차적으로 실행시키는 것이다. 하나의 명령어로 말이다.
그래서 특별히 어려운 것은 없고 mina의 사용 방법과 설정 파일들의 내용들을 아는 것이 중요하다.
1) gemfile에 mina 추가
2) bundle install
3) mina init (config/deploy.rb가 생성됨)
3) mina setup (config 폴더 내에 deploy.rb 파일이 있는 곳에 가서)
4) mina deploy (config 폴더 내에 deploy.rb 파일이 있는 곳에 가서)
이렇게 순서대로만 하면 되는데(deploy.rb 파일 내용은 아래 참고) 이 순서들 하나하나의 의미도 궁금하니까 따로 정리해보았다.
# 1) mina gem 을 설치
# $ gem install mina
# 2) Gemfile에 gem 'mina'추가
# 3) Let's generate the deploy.rb file. For this, run mina init in the rails application folder:
# $ mina init
# 4) et's open the file and configure the server:
# vi config/deploy.rb
# 5) deploy.rb 파일 작성
# Verbose command will let you see what's happening in this phase,
# and if something goes wrong here, you will see exactly which command fails.
# 6) mina setup --verbose
실제로 '$ mina setup --verbose' 라고 명령시 아래와 같은 일들이 발생
여러 폴더를 만들어 주는데 핵심이 되는 3개의 폴더는
배포 경로에 써둔 디렉토리, 해당 디렉토리 아래에 releases, shared까지 총 3개
mina setup --verbose
-----> Setting up /home/ec2-user/MinaDeployTestMyApp
$ mkdir -p "/home/ec2-user/MinaDeployTestMyApp"
$ mkdir -p "/home/ec2-user/MinaDeployTestMyApp/releases"
$ mkdir -p "/home/ec2-user/MinaDeployTestMyApp/shared"
$ cd /home/ec2-user/MinaDeployTestMyApp/shared
$ mkdir -p "vendor/bundle"
$ mkdir -p "log"
$ mkdir -p "tmp/cache"
$ mkdir -p "public/assets"
/home/ec2-user
$ if [ -x "$(command -v tree)" ]; then tree -d -L 2 "/home/ec2-user/MinaDeployTestMyApp"; else ls -al "/home/ec2-user/MinaDeployTestMyApp"; fi
합계 16
drwxrwxr-x 4 ec2-user ec2-user 4096 9월 26 01:49 .
drwx-----x 15 ec2-user ec2-user 4096 9월 25 02:41 ..
drwxrwxr-x 2 ec2-user ec2-user 4096 9월 26 01:49 releases
drwxrwxr-x 6 ec2-user ec2-user 4096 9월 26 01:49 shared
$ if ! ssh-keygen -H -F github.com &>/dev/null; then
ssh-keyscan -t rsa -p 22 -H github.com >> ~/.ssh/known_hosts
fi
# github.com:22 SSH-2.0-babeld-c9de8699
Connection to ec2-13-209-64-175.ap-northeast-2.compute.amazonaws.com closed.
Elapsed time: 1.64 seconds
# 서버 환경 세팅
# 7) mina remote_environment 와 같은 커맨드로 미리 설정해둔 설정 그대로 세팅되게 하는 방법이 있지만
# 그냥 서버에 직접 들어가서 세팅해놓고 난 뒤 deploy 하는 것이 더 좋은 것 같다
# deploy 전에 이걸 하는 이유는 deploy 단계에서 'bundle' 명령어를 사용하게 되는데 이전에 bundler가 설치가 되어야 하고
# 이런 deploy과정 전에 이뤄져야할 여러 과정들을 deploy.rb에 미리 세팅해둘지, 서버가서 직접 해둘지는 본인 선택 몫이다.
# $ git clone git://github.com/sstephenson/rbenv.git .rbenv
# $ git clone git://github.com/sstephenson/ruby-build.git
# .bashrc에 아래 내용 추가
# export RBENV_ROOT="${HOME}/.rbenv"
# if [ -d "${RBENV_ROOT}" ]; then
# export PATH="${RBENV_ROOT}/bin:${PATH}"
# eval "$(rbenv init -)"
# fi
# source .bash_profile -> rbenv install 2.x.x -> rbenv global 2.x.x -> rbenv rehash
# Trace command will show backtraces when errors occur.
# 8) mina deploy --trace
# ==> 배포가 완료됨
이게 다다. 그리고 코드가 수정되게 되면 4번인 'mina deploy'만 다시 해주면 된다. 정말 엄청나게 간단하다.
mina를 사용한 배포에 있어 가장 중요한 것은 아래의 deploy.rb에 대한 내용이다. deploy.rb파일에 채워놓는 내용들이 'mina + 명령어'를 통해 이뤄질 수행 내용들이다.
# set : 의 경우 mina가 구동하는데 필요한 데이터들이 세팅되는 것이고
# task : ~ do 의 경우 mina command(deploy, setup, environment ..) 에 따라 각각 작동함
# Set the domain or ip address of the remote server.
# 원격 서버상(예시:aws의 instance)의 도메인이나 ip 주소
set :domain, 'xxx.xxx.xxx.xxx'
# Set the folder of the remote server where Mina will deploy your application.
# Mina가 application을 배포할 원격 서버상의 폴더 주소
set :deploy_to, '/home/ec2-user/surhommekim'
# Set a link to the repository. Example: git@bitbucket.pixelpoint/myapp.git
# 원격 리포지토리의 git 주소(git 홈페이지 상에 나오는 url 주소)
set :repository, 'https://github.com/KIMJUNGKWON/ProgrammingRuby.git'
# Set the name of a branch you plan to deploy as default master.
# 위 repository 에서 설정한 git의 어떤 branch에서 가져올지 설정(보통 master)
set :branch, 'master'
# Fill in the names of the files and directories that will be symlinks to the shared directory.
# All folders will be created automatically on Mina setup.
# 공유되고 있는 디렉토리와 symlink될 파일들과 디렉토리들을 명시
# shared_dirs, shared_files 들을 fetch한 후에 명시된 dirs,files에 push해준다
# shared_* 의 경우 아래 deploy에서 "invoke :'deploy:link_shared_paths'"에 의해 정의된 .bin/link_shared_paths 에 의해 결정됨
# 'shared_dirs', 'shared_files'는 mina에 의한 고유값 자체이다
set :shared_dirs, fetch(:shared_dirs, []).push('log', 'tmp/pids', 'tmp/sockets', 'public/uploads')
set :shared_files, fetch(:shared_files, []).push('config/database.yml', 'config/secrets.yml', 'config/puma.rb')
# Username of ssh user for access to the remote server.
# 리모트 서버에 접근하기 위한 ssh user의 username
# ssh -i surhommekim.pem ec2-user@xx.xx.xx.xx 에서 ec2-user를 의미
set :user, 'ec2-user'
# This is not a required field. You can use it to set an application name for easy recognition.
# application 이름을 설정하는 곳으로 필수는 아님
set :application_name, 'SurhommekimApplication'
# Set ruby version. If you have RVM installed globally, you’ll also need to set an RVM path,
# like: set :rvm_use_path, '/usr/local/rvm/scripts/rvm'.
# You can find the RVM location with the rvm info command.
# ruby버전 세팅
task :environment do
invoke :'rvm:use', 'ruby-2.4.1'
end
# Put any custom commands you need to run at setup
# All paths in `shared_dirs` and `shared_paths` will be created on their own.
task :setup do
command %[touch "#{fetch(:shared_path)}/config/database.yml"]
command %[touch "#{fetch(:shared_path)}/config/secrets.yml"]
command %[touch "#{fetch(:shared_path)}/config/puma.rb"]
comment "Be sure to edit '#{fetch(:shared_path)}/config/database.yml', 'secrets.yml' and puma.rb."
end
task :deploy do
deploy do
invoke :'git:clone'
invoke :'deploy:link_shared_paths' # Creates symbolic links to paths in shared_paths setting.
invoke :'bundle:install'
invoke :'rails:db_migrate'
invoke :'rails:assets_precompile' # css, js 압축하여 갖도록해줌. 이걸 하지 않으면 캐시값을 사용해서 수정사항 미반영될 수 있음
invoke :'deploy:cleanup' # Cleaning up old releases
on :launch do
invoke :"unicorn:restart"
end
end
end
나는 써보니 굉장히 유용했는데, 이게 찾다보니 2017년도 이후로 버전업이 안된 것 같다. 젠킨스 같은 것으로 다 갈아 탔는지 뭐, 루비 단톡방에 질문을 올려도 mina를 쓰는 사람이 없어서 답변을 얻지 못하였고 그래서 구글링을 했는데 한국인이 mina에 대해 자세히 써둔 글이 없었다. 외국인이 써둔 글들이 좀 있긴 했는데 약간 코드몽키성(이렇게 하면 이렇게 된다)의 가이드 밖에 없어서 결국 내가 여기저기 뒤져서 조합해서 각각의 의미를 정리해보았다.
참고 사이트)
https://www.digitalocean.com/community/tutorials/how-to-use-mina-to-deploy-a-ruby-on-rails-application
https://medium.com/pixelpoint/deploy-rails-application-with-mina-nginx-and-puma-96a9caac9078