How to create an application server on an EC2 instance on AWS

Introduction

AWS is an abbreviation for Amazon Web Servises, which is a cloud server service provided by Amazon. We will output what we have learned in order to improve our understanding of AWS.

This flow

It is assumed that you have created an instance.

Install Unicorn in your application

① Install Unicorn in your own application

Add the following description to the Gemfile in the application.

Gemfile


group :production do
    gem 'unicorn', '5.4.1'
end

Terminal


% bundle install

② Unicorn settings

Create unicorn.rb in your application's config. Then, make the following settings.

config/unicorn.rb


#Put the directory where the application code on the server is installed in a variable
app_path = File.expand_path('../../', __FILE__)

#Determine application server performance
worker_processes 1

#Specify the directory where the application is installed
working_directory app_path

#Specify the location of the files required to start Unicorn
pid "#{app_path}/tmp/pids/unicorn.pid"

#Specify the port number
listen 3000

#Specify a file to log errors
stderr_path "#{app_path}/log/unicorn.stderr.log"

#Specify the file to record the normal log
stdout_path "#{app_path}/log/unicorn.stdout.log"

#Set maximum time to wait for Rails application response
timeout 60

#The following is an applied setting, so the explanation is omitted.

preload_app true
GC.respond_to?(:copy_on_write_friendly=) && GC.copy_on_write_friendly = true

check_client_connection false

run_once = true

before_fork do |server, worker|
  defined?(ActiveRecord::Base) &&
    ActiveRecord::Base.connection.disconnect!

  if run_once
    run_once = false # prevent from firing again
  end

  old_pid = "#{server.config[:pid]}.oldbin"
  if File.exist?(old_pid) && server.pid != old_pid
    begin
      sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
      Process.kill(sig, File.read(old_pid).to_i)
    rescue Errno::ENOENT, Errno::ESRCH => e
      logger.error e
    end
  end
end

after_fork do |_server, _worker|
  defined?(ActiveRecord::Base) && ActiveRecord::Base.establish_connection
end

Push it to the remote repository and reflect it.

Create an application server on an instance created with EC2 on AWS

③ Install the application on the instance

Terminal


Log in to your instance
% ssh -i key pair name.pem ec2-user@<Public IP>

In the instance/var/www/Creating a directory
[instance]$ sudo mkdir /var/www/

Ec2 permissions on the created www directory-Granted to user
[instance]$ sudo chown ec2-user /var/www/

Go to www directory
[instance]$ cd /var/www/

#Clone application from GitHub
[Instance www]$ git clone <HTTPS URL obtained from the Code button of the application you want to deploy on GitHub>

④ Install Gem

Terminal


Move to your home directory in your instance
[Instance www]$ cd ~

Swap file settings
[instance]$ sudo dd if=/dev/zero of=/swapfile1 bs=1M count=512
[instance]$ sudo chmod 600 /swapfile1
[instance]$ sudo mkswap /swapfile1
[instance]$ sudo swapon /swapfile1
[instance]$ sudo sh - -c 'echo "/swapfile1  none        swap    sw              0   0" >> /etc/fstab'

Terminal


Go to the application directory in your instance
[instance]$ cd /var/www/<Application name>

Install bundler(The version of bundler is "command" in the terminal+Create another tab with "T" and "bundler" in the newly created tab-You can check it by executing "v")
[instance<Application name>]$ gem install bundler -v <bundler version>

Install Gem
[instance<Application name>]$ bundle install

Production environment settings

⑤ Environment variable settings

For security reasons, database passwords etc. are not uploaded to GitHub. Such information is set using "environment variables".

What is secret_key_base

A character string used to encrypt cookies. Required for running Rails applications in production.

Terminal


[instance<Application name>]$ rake secret
=> secret_key_The character string that becomes the base is displayed

Move to your home directory within the instance
[instance<Application name>]$ cd ~

/etc/Edit environment
[instance]$ sudo vim /etc/environment

Type "i" to enter input mode

Enter the password of the root user of the configured database
DATABASE_PASSWORD='Database root user password'
SECRET_KEY_BASE='The secret created earlier_key_base'

* If you are using AWS S3, enter the following (enter the value referring to the CSV file downloaded when setting S3)
AWS_ACCESS_KEY_ID='Copy the value of Access key ID in the CSV file here'
AWS_SECRET_ACCESS_KEY='Copy the value of Secret access key in the CSV file here'

* If you have introduced Basic authentication, enter the following (enter the set user name and password)
BASIC_AUTH_USER='Set user name'
BASIC_AUTH_PASSWORD='Password set'

「:Save as "wq"

Log out of the instance and log in again for the environment variables to take effect
[instance]$ exit
% ssh -i key pair name.pem ec2-user@<Public IP>

Checking environment variables
[Instance re]$ env
=>OK when the settings set above are displayed.

⑥ Release the port to the security group

In the AWS Management Console, add "Port 3000" and "Source 0.0.0.0/0" of "Custom TCP" to the inbound rule of the security group of the instance.

⑦ Change Rails application settings

You must also set the environment variables you set in your instance above in your application.

:config/database.yml


production:
  <<: *default
  database:(* Do not edit here)
  username: root
  password: <%= ENV['DATABASE_PASSWORD'] %>
  socket: /var/lib/mysql/mysql.sock

After changing the settings, push to GitHub.

Then let the instance reflect the changes in your application.

Terminal


Move to the application directory within the instance
[instance]$ cd /var/www/<Application name>

Reflect application setting changes
[instance<Application name>]$ git pull origin master

Launch application

⑧ Create database (if database server exists in instance)

Please refer to here for how to create a database server https://qiita.com/daisuke30x/items/7501d724a0727ad9f2e4

Terminal


Creating a database
[instance<Application name>]$ rails db:create RAILS_ENV=production
[instance<Application name>]$ rails db:migrate RAILS_ENV=production

Start database
[instance<Application name>] $ sudo systemctl start maradb

RAILS_ENV = production is an option to specify the production environment

⑨ Start application

Terminal


[instance<Application name>]$ bundle exec unicorn_rails -c config/unicorn.rb -E production -D

Compile your application's asset files (CSS, JavaScript, images, etc.). This is a necessary task in a production environment.

Terminal


[instance<Application name>]$ rails assets:precompile RAILS_ENV=production

Terminal


Check the process
[instance<Application name>]$ ps aux | grep unicorn
=>The second number from the left is the process ID

Process stop
[instance<Application name>]$ kill <unicorn_Rails master process ID>

Launch the application again
[instance<Application name>]$ RAILS_SERVE_STATIC_FILES=1 unicorn_rails -c config/unicorn.rb -E production -D

"RAILS_SERVE_STATIC_FILES = 1" is the role that specifies that the compiled asset file can be found.

** Enter "http: // : 3000 /" or "http: // : 3000 /" in the browser, and if the application is displayed, it is successful. ** **

Finally

We hope that this post will help beginners review.

Recommended Posts

How to create an application server on an EC2 instance on AWS
How to create a web server on an EC2 instance on AWS
How to install Ruby on an EC2 instance on AWS
How to create an application
How to publish an application using AWS (3) EC2 instance environment construction
How to publish an application on Heroku
How to handle an instance
Deploy laravel using docker on EC2 on AWS ① (Create EC2 instance)
Deploy SpringBoot application to AWS EC2
How to deploy a Rails application on AWS (article summary)
How to install and use Composer on an ECS instance on Ubuntu 16.04
How to send push notifications on AWS
Volume of trying to create a Java Web application on Windows Server 2016
How to deploy a container on AWS Lambda
How to save images on Heroku to S3 on AWS
Build a Laravel environment on an AWS instance
Rails6.0 ~ How to create an eco-friendly development environment
I tried installing docker on an EC2 instance
Notes on how to create Burp Suite extensions
How to create an oleore certificate (SSL certificate, self-signed certificate)
How to create docker-compose
[Rails] Create an application
Memo to build a Servlet environment on AWS EC2
List how to learn from Docker to AKS on AWS
(Ruby on Rails6) How to create models and tables
[AWS] Link memory usage of Ubuntu EC2 instance to CloudWatch
How to deploy on heroku
How to get inside a container running on AWS Fargate
Sample to create one-time password on server side and client side
How to deploy a kotlin (java) app on AWS fargate
Install docker on AWS EC2
How to terminate rails server
How to create an environment that uses Docker (WSL2) and Vagrant (VirtualBox) together on Windows
How to develop an app with Jersey Java RESTful API on Alibaba Cloud ECS instance
How to run React and Rails on the same server
How to create a method
How to make an application with ruby on rails (assuming that the environment has been built)
How to run a mock server on Swagger-ui using stoplight/prism (using AWS/EC2/Docker)
[Rails / Heroku / MySQL] How to reset the DB of Rails application on Heroku
How to place and share SwiftLint config files on the server
How to build an Apache Flink application from scratch in 5 minutes
How to deploy jQuery on Rails
Preparing to create a Rails application
How to "hollow" View on Android
[Java] How to update Java on Windows
How to install ImageMagick on Windows 10
How to use Ruby on Rails
To beginners launching Docker on AWS
Build a Minecraft server on AWS
How to deploy Bootstrap on Rails
How to run JavaFX on Docker
How to use Bio-Formats on Ubuntu 20.04
[Java] How to create a folder
How to insert an external library
How to install MariaDB 10.4 on CentOS 8
Rails on Tiles (how to write)
How to install WildFly on Ubuntu 18.04
How to build vim on Ubuntu 20.04
[Rails] AWS EC2 instance environment construction
[For beginners] Laravel Docker AWS (EC2) How to easily deploy a web application (PHP) from 0 (free) ①-Overview-
Easy way to create an original logo for your application (easy with your smartphone)