Skip to content

Rails Production Configuration

Eugene Khashin edited this page Oct 2, 2018 · 1 revision

Тех.стэк

Nginx - latest

RVM - latest (1.29)

Ruby - 2.5.1

Rails - 5.2.1

PostgreSQL - 9.5

Redis - 3.0

Sidekiq Gem - latest

Dotenv Gem - latest

Переменные окружения

Используется Dotenv Gem, обязательно в проекте в application.rb сделать Dotenv::Railtie.load перед декларацией модуля приложения. В корне проекта должен быть .env.production файл, который должен быть .gitignore.

Сервисы

PostgreSQL

Redis

sidekiq.service

APPNAME - название запускаемого приложения

[Unit]
Description=Sidekiq App Server
After=network.target

[Service]
EnvironmentFile=/var/www/APPNAME/.env.production
Type=simple
User=deployer
Group=deployer
WorkingDirectory=/var/www/APPNAME
ExecStart=/bin/bash -lc '/home/deployer/.rvm/rubies/ruby-2.5.1/lib/ruby/gems/2.5.0/bin/bundle exec sidekiq -e production -C /var/www/APPNAME/config/sidekiq.yml'
Restart=always

[Install]
WantedBy=multi-user.target

rails.service

[Unit]
Description=Rails HTTP Server
After=network.target

[Service]
Type=forking

User=deployer
Group=deployer
ExecStart=/usr/bin/rails_restart
ExecStop=

Restart=always

[Install]
WantedBy=multi-user.target

/usr/bin/rails_restart

#!/bin/bash

echo "Start rails application updating process"
APP_DIR=/var/www/APPNAME
CONF_DIR="${APP_DIR}/deploy/config"
UPSTREAM_CONFIG_FILE="${CONF_DIR}/UPSTREAM_SERVERS"
APP_PIDS_DIR=/var/run/APPNAME
PORT1=3000
PORT2=3001

echo "Check for currently running app"
echo "Determine if ${PORT1} port is listening"
#RC=`ss -lnt src :${PORT1} | tail -n+2 | wc -l`
PORT=$(cat ${CONF_DIR}/PORT)
if [ "$PORT" = "3000" ]; then
  echo "TCP port ${PORT1} is listening, try to run new app on port ${PORT2}"
  PORT=$PORT1
  NEW_PORT=$PORT2
else
  echo "TCP port ${PORT1} is not listening, try to run new app on it"
  PORT=$PORT2
  NEW_PORT=$PORT1
fi

echo "Ensure PID directory is exists"
sudo mkdir -p ${APP_PIDS_DIR}
sudo chown root: ${APP_PIDS_DIR}
sudo chmod 777 ${APP_PIDS_DIR} 

echo "Starting new process on port ${NEW_PORT}"
cd $APP_DIR
/bin/bash -l -i -c "cd $APP_DIR && rails s -e production -P $APP_PIDS_DIR/$NEW_PORT.pid -p $NEW_PORT -d"

echo "Waiting"
sleep 3

echo "Killing old process"
CURRENT_PID_FILE=$APP_PIDS_DIR/$PORT.pid
if [ -f ${CURRENT_PID_FILE} ]; then
  echo "Found old PID file ${CURRENT_PID_FILE}"
  CURRENT_PID=$(cat $CURRENT_PID_FILE)
  kill -9 $CURRENT_PID
else
  echo "Old PID file ${CURRENT_PID_FILE} not found, old process won't be killed"
fi

echo "$(date +%s%N) Updating Nginx config and reloading Nginx"
echo "Write upstream servers info to ${UPSTREAM_CONFIG_FILE}"
echo -e "server 127.0.0.1:$NEW_PORT;\nserver 127.0.0.1:$PORT;" > $UPSTREAM_CONFIG_FILE
echo -e "$NEW_PORT" > ${CONF_DIR}/PORT
sudo nginx -s reload