1
0

Next.js+rails7+mysql8.0で環境を構築する

Last updated at Posted at 2024-07-27

https://qiita.com/gabakugik/items/edcc2f4950e5cd94185a
これの続きです。

railsの構築

ツリー構造

|-- backend
|   |-- Dockerfile
|   |-- Gemfile
|   |-- Gemfile.lock
|   |-- README.md
|   |-- Rakefile
|   |-- app
|   |-- bin
|   |-- config
|   |-- config.ru
|   |-- db
|   |-- lib
|   |-- log
|   |-- public
|   |-- storage
|   |-- test
|   |-- tmp
|   `-- vendor
|-- docker-compose.yml
`-- frontend
    |`-- app
`-- Dockerfile(フロント用)

backendの中に入り

Dockerfile
FROM ruby:3.2

ENV LANG=C.UTF-8 \
  TZ=Asia/Tokyo

WORKDIR /app
RUN apt-get update -qq && apt-get install -y nodejs default-mysql-client
COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install

CMD ["rails", "server", "-b", "0.0.0.0"]

backend/Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 7.0.5'

docker-compose.ymlに戻り
修正

docker-compose.yml

version: '3.8'
services:
  db:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: password
    ports:
      - 3306:3306
    volumes:
      - mysql-db:/var/lib/mysql
  backend:
    tty: true
    depends_on:
      - db
    build:
      context: ./backend/
      dockerfile: Dockerfile
    ports:
      - 3000:3000
    volumes:
      - ./backend:/app
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
  frontend:
    build:
      context: ./frontend/
      dockerfile: Dockerfile
    volumes:
      - ./frontend:/app
    command: 'yarn dev'
    ports:
      - '3001:3001'
volumes:
  mysql-db:
    driver: local
docker compose run backend rails new . --api --force --no-deps --database=mysql
./backend/config/database.yml
default: &default
  adapter: mysql2
  encoding: utf8mb4
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: root
  password: password # デフォルトだと空欄になっているはずなので変更
  host: db # デフォルトだとlocalhostになっているはずなので変更

development:
  <<: *default
  database: myapp_development

test:
  <<: *default
  database: myapp_test

production:
  <<: *default
  database: <%= ENV["DATABASE_NAME"] %>
  username: <%= ENV["DATABASE_USERNAME"] %>
  password: <%= ENV["DATABASE_PASSWORD"] %>
$ docker compose build
$ docker compose up -d
$ docker compose run backend bundle exec rails db:create

これでcompose.ymlでlocalhost:3001でnext.js、localhost:3000でrailsが表示されるはずです。

ぜひやってみてください。

1
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
1
0