0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Docker, docker-compose, rails を使って、HelloWorld を表示する。

Posted at

目的

docker, docker-compose, rails を使って、HelloWorld を表示する。

環境

EC2 ubuntu

前提

・Vscode の Remote SSH を使う。
・3000 ポートのポートフォワーディングができている。

手順

(1)

~$ sudo apt update
~$ sudo apt install docker.io docker-compose
~$ sudo systemctl start docker
~$ sudo systemctl enable docker
~$ mkdir rails_api

vscode で rails_api フォルダに移動

~/rails_api$ docker-compose --version
~/rails_api$ sudo apt remove docker-compose
~/rails_api$ DOCKER_COMPOSE_VERSION=2.20.3
~/rails_api$ sudo curl -SL https://github.com/docker/compose/releases/download/v${DOCKER_COMPOSE_VERSION}/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
~/rails_api$ sudo chmod +x /usr/local/bin/docker-compose
~/rails_api$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
~/rails_api$ docker-compose version

(2)
docker-compose コマンドを実行するために、ubuntuユーザにdockerグループを割り当てる。
ただ、sudo をつければ実行できるので、必要ないかも。

~/rails_api$ groups
~/rails_api$ sudo usermod -aG docker $USER
~/rails_api$ newgrp docker

(3)
下記のように ~/rails_api にファイルを作成。

# Dockerfile
FROM ruby:3.2

RUN apt-get update -qq && apt-get install -y nodejs

WORKDIR /my_app

COPY Gemfile Gemfile.lock ./
RUN gem install bundler && bundle install

COPY . .
docker-compose.yml
version: '3'
services:
  web:
    build: .
    ports:
      - "3000:3000"
    volumes:
      - .:/my_app
    command: rails s -b 0.0.0.0
# Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 7.0.0'
Gemfile.lock
# 空で作成

(4)

~/rails_api$ docker-compose run --no-deps web rails new . --api --force
~/rails_api$ docker-compose run web bundle install

(5)

echo $USER
sudo chown -R $USER:$USER ./

下記のようにファイル作成

app/controllers/hello_controller.rb
class HelloController < ApplicationController
  def index
    render plain: "HelloWorld"
  end
end
config/routes.rb
Rails.application.routes.draw do
  get 'hello', to: 'hello#index'
end

(6)
ビルドして起動する。

~/rails_api$docker-compose build
~/rails_api$docker-compose up

(7)
http://localhost:3000/hello にアクセスする。

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?