VSCodeとDev ContainerでRuby on Railsを始める
はじめに
- MacBook Pro (Apple M1 Max)
- macOS Ventura 13.6.2
- Docker Desktop v4.25.2
- VSCode v1.84.2
- 拡張機能 Dev Containers v0.321.0
フォルダ構造と各ファイル
1
2
3
4
5
6
7
|
./sampleapp
└── .devcontainer
├── Dockerfile
├── Gemfile
├── Gemfile.lock
├── devcontainer.json
└── docker-compose.yml
|
.devcontainer/Dockerfile
1
2
3
4
5
6
7
8
9
10
11
|
FROM ruby:3.2.2
ENV ROOT="/workspace"
ENV LANG=C.UTF-8
ENV TZ=Asia/Tokyo
WORKDIR ${ROOT}
COPY Gemfile ${ROOT}
RUN gem install bundler
RUN bundle install --jobs 4
|
.devcontainer/Gemfile
1
2
3
4
5
|
source "https://rubygems.org"
ruby "3.2.2"
gem "rails", "7.1.2"
|
.devcontainer/Gemfile.lock
特になし。touch Gemfile.lockしただけ。
.devcontainer/docker-compose.yml
MySQLを使いたい。
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
|
version: '3'
services:
app:
build:
context: .
dockerfile: Dockerfile
volumes:
- ..:/workspace:cached
- bundle-volume:/usr/local/bundle
ports:
- 3000:3000
depends_on:
- db
tty: true
stdin_open: true
db:
image: mysql:8
volumes:
- mysql-volume:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: password
TZ: "Asia/Tokyo"
ports:
- "3306:3306"
volumes:
bundle-volume:
mysql-volume:
|
.devcontainer/devcontainer.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
{
"name": "Ruby",
"dockerComposeFile":[
"docker-compose.yml"
],
"service": "app",
"workspaceFolder": "/workspace",
"customizations": {
"vscode": {
"extensions": [
"shopify.ruby-lsp"
]
}
}
}
|
コンテナ作成
VSCodeのDev Containerの機能を実行するだけだ。
コマンドパレット(Shift+Command+p or F1)を開き、
Dev Containers: Rebuild and Reopen in Container を選択する。
しばらくすると、コンテナが出来上がる。Docker Desktopで確認すると以下のようになる。
プロジェクト作成
Railsのプロジェクトを作成して、ウェブサーバーを起動する。
1
2
3
|
rails new app1 --minimal
cd app1
bin/rails server
|
http://127.0.0.1:3000
にアクセスする。
参考資料
- Using Images, Dockerfiles, and Docker Compose - container.dev
- Dev Container metadata reference - container.dev
- How to use Docker containers for Ruby on Rails development in Visual Studio Code - DEV Community
- Developing Rails Apps in a Dev Container with VS Code | End Point Dev
- Starting a Rails app using vscode containers - DEV Community