Windows10でWSLを使ってUbuntu環境で、DockerのRails開発環境を整える。
背景
Dockerを利用してRailsの開発環境を構築していたが、様々なエラーが発生。
参照サイトでの説明がLinux環境をもとにしたものが多かったので、Windows用に翻訳する手間が必要で大変だった。
そこで、自分もWSLを利用してLinux環境(Ubuntu)で開発をすることにした。
目標
HerokuにRailsアプリケーションをデプロイする。
VSCodeでLinux開発環境を構築
下記サイトを参考にVSCodeでLinux開発環境を使えるようにした。
【WSL / WSL2】VSCode×WSLでWindows上にLinux開発環境を構築
herokuログインでエラー
VSCodeでの環境構築後、herokuにログインしようとすると、下記エラーが発生。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ heroku login
/mnt/c/Program Files/heroku/bin/../client/bin/heroku.cmd: 1: @echo: not found
/mnt/c/Program Files/heroku/bin/../client/bin/heroku.cmd: 2: setlocal: not found
/mnt/c/Program Files/heroku/bin/../client/bin/heroku.cmd: 4: Syntax error: "(" unexpected (expecting "then")
herokuコマンドにはsudoが必要
herokuコマンドにはsudoが必要だったが、herokuがないと言われる。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo heroku login
sudo: heroku: command not found
参考
heroku CLIを公式サイトからインストールしようとするも、エラー。
heroku公式サイトからインストールしようとするも、エラーが発生。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo snap install --classic heroku
Interacting with snapd is not yet supported on Windows Subsystem for Linux.
This command has been left available for documentation purposes only.
エラーを翻訳すると、「snapd との相互作用は、Windows Subsystem for Linux ではまだサポートされていません。このコマンドは文書化の目的でのみ使用可能です。
」とのこと。
そこで、スタンドアロンインストールを試してみる。
参考
スタンドアロンインストールを試してみる。
先ほどのheroku公式サイトのダウンロードページを下にスクロールすると、スタンドアロンインストールというものがあり、
Docker コンテナ内ではこの方法をお勧めします。
とのことですので、こちらのインストールを試します。
結果、無事herokuをインストールできました。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ curl https://cli-assets.heroku.com/install.sh | sh
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 1892 100 1892 0 0 2509 0 --:--:-- --:--:-- --:--:-- 2509
This script requires superuser access.
You will be prompted for your password by sudo.
[sudo] password for masa:
Installing CLI from https://cli-assets.heroku.com/heroku-linux-x64.tar.xz
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 18.2M 100 18.2M 0 0 163k 0 0:01:54 0:01:54 --:--:-- 2727k
v12.16.2
heroku installed to /usr/local/bin/heroku
› Warning: Our terms of service have changed: https://dashboard.heroku.com/terms-of-service
heroku/7.47.6 linux-x64 node-v12.16.2
下の方に出てきたWarningを確認すると、利用規約変更のお知らせでした。
再び、herokuログインに挑戦。
参考
再び、herokuログインを試みるも、エラー。
ブラウザを開けませんという警告が出ている。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo heroku login
heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/a3b0501f-1fe7-410f-89b7-21278b86a9b9?requestor=SFMyNTY.g2gDbQAAAAs2MC43MC45LjE0OW4GAIivKMV2AWIAAVGA.NqLuDadHMLIEetI3_8hxIXLUDumfhs6VG4iuK27UeFc
Error: spawn cmd.exe ENOENT
Code: ENOENT
› Warning: Cannot open browser.
heroku: Waiting for login... ⣯
エラーを検索して、出てきたサイトを確認する。
herokuログインに成功する。
--interactive
オプションをつけることによって、ブラウザを開かずにCLI上でログインできました。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo heroku login --interactive
heroku: Enter your login credentials
Email: mailadress@gmail.com
Password: *********
Logged in as mailadress@gmail.com
ログインができたので、下記サイトの手順に従って、herokuデプロイ作業を進めます。
Herokuでアプリケーションをデプロイするまでの流れ rails編
参考
heroku - アプリケーションの作成
heroku create [アプリケーション名]
を実行。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo heroku create masa-rails-tutorial-20210103
Creating ⬢ masa-rails-tutorial-20210103... done
https://masa-rails-tutorial-20210103.herokuapp.com/ | https://git.heroku.com/masa-rails-tutorial-20210103.git
masa@DESKTOP-0CNPS43:~/RailsTutorial$
成功しました。
次は、prodcution.rb
を編集します。
参考
prodcution.rbを編集しようとすると、3つのエラーが発生。
Failed to start Solargraph: /bin/bash: /mnt/c/Ruby27-x64/bin/solargraph: C:/Ruby27-x64/bin/ruby.exe: bad interpreter: No such file or directory
Couldn't start client Ruby Language Server
-
couldn't find rubocop for formatting (ENOENT)
ubuntuにruby等をインストールしていなかったので、これらエラーが発生しているのかと考え、下記サイトを参考にubuntu環境にruby等をインストールする。
Ruby 歴 10 年の私が【絶対に】 gem install rails コマンドを実行しない理由
Ubuntu環境へのRuby等のインストールは完了したが、まだエラーが発生する。
参考サイトにて、Ruby等のインストールは完了。
(rbenv install 2.6.2
は処理時間が長く、エラーが起きているのかと思ったが、10分程度かかるとのことで、放置して、無事終了した。)
しかし、まだエラーが出る。
①のエラー内容が少し変わっているので、それを確認する
Failed to start Solargraph:
Couldn't start client Ruby Language Server
-
couldn't find rubocop for formatting (ENOENT)
参考
solargraphをインストールすると、エラー解消された。
solargraph -v
で確認すると、ファイルがなかったため、
gem install solargraph
でインストール。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ solargraph -v
bash: /mnt/c/Ruby27-x64/bin/solargraph: C:/Ruby27-x64/bin/ruby.exe: bad interpreter: No such file or directory
masa@DESKTOP-0CNPS43:~/RailsTutorial$ gem install solargraph
VSCodeを開いても、エラーが出なくなりました!
prodcution.rb
の編集を再開します。
gitへのcommit時のエラー
prodcution.rb
を編集してgitへcommitをしようとすると、
Git の 'user.name' と 'user.email' を更生していることを確認してください。
というエラーが発生。
下記コードを実行して、ユーザー名、メールアドレスを登録。
git config --global user.name "[ユーザー名]"
git config --global user.email [メールアドレス]
masa@DESKTOP-0CNPS43:~/RailsTutorial$ git config --global user.name "MASA"
masa@DESKTOP-0CNPS43:~/RailsTutorial$ git config --global user.mail mailaddress@gmail.com
次は、「rails - プリコンパイル」へ進む。
rails - プリコンパイル時のエラー
railsのプリコンパイル時にエラー「ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `bin/rails credentials:edit`
」が発生。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ rake assets:precompile RAILS_ENV=production
rake aborted!
ArgumentError: Missing `secret_key_base` for 'production' environment, set this string with `bin/rails credentials:edit`
/home/masa/RailsTutorial/config/environment.rb:5:in `<main>'
Tasks: TOP => environment
(See full trace by running task with --trace)
EDITOR="vi" bin/rails credentials:edit
でconfig/master.key
を作成。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ EDITOR="vi" bin/rails credentials:edit
Adding config/master.key to store the encryption key: 541...
Save this in a password manager your team can access.
If you lose the key, no one, including you, can access anything encrypted with it.
create config/master.key
File encrypted and saved.
この後、プリコンパイルが正常にしました。
次は、「rails - マイグレーション」へと進みます。
参考
rails - マイグレーションでのエラー
rake db:migrate RAILS_ENV=production
を実行すると、下記エラーが発生。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ rake db:migrate RAILS_ENV=production
rake aborted!
ActiveRecord::ConnectionNotEstablished: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
postgresqlが見つからない。
ローカル環境ではなく、コンテナ環境で実行してみる。
docker-compose exec web rake db:migrate RAILS_ENV=production
が、エラーとなる。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ docker-compose exec web rake db:migrate RAILS_ENV=production
The command 'docker-compose' could not be found in this WSL 1 distro.
We recommend to convert this distro to WSL 2 and activate
the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
翻訳すると、
コマンド 'docker-compose' はこの WSL 1 ディストリビューションでは見つかりませんでした。このディストロをWSL 2に変換し、Docker Desktopの設定でWSLの統合を有効にすることをお勧めします。
詳細は https://docs.docker.com/docker-for-windows/wsl/ を参照してください。
とのこと。
なので、https://docs.docker.com/docker-for-windows/wsl/を参照して、①WSL2にconvertする。及び、②Docker Desktopの設定でWSLの統合を有効にする。
①WSL2にconvertする。
参考サイトを上から順に作業した結果、wsl --list --verbose
でバージョン情報を確認すると、UbuntuのWSLのバージョンが1になっていたので、wsl --set-version Ubuntu 2
でWSLのバージョンを2に変換しました。
参考サイト
Windows Subsystem for Linux Installation Guide for Windows 10
②Docker Desktopの設定でWSLの統合を有効にする。
インストール時に既にWSL2を有効化にしていました。
(そういえば、インストール時にWSL2をインストールした記憶をうっすら思い出しました。。)
参考サイト
再度実行するも同じエラー
UbuntuをWSL2にconvertして、Docker Desktopの設定でWSL2を有効化したが、同じエラー。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ docker-compose exec web rake db:migrate RAILS_ENV=production
The command 'docker-compose' could not be found in this WSL 2 distro.
We recommend to activate the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
『②Docker Desktopの設定でWSLの統合を有効にする。』ができていなかった。
Settings
>Resources
>WSL INTEGRATION
でUbuntu
との統合を有効化。
docker-compose exec web rake db:migrate RAILS_ENV=production
は起動したが、大量のパーミッションエラーが発生。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ docker-compose exec web rake db:migrate RAILS_ENV=production
Traceback (most recent call last):
File "urllib3/connectionpool.py", line 677, in urlopen
File "urllib3/connectionpool.py", line 392, in _make_request
File "http/client.py", line 1252, in request
File "http/client.py", line 1298, in _send_request
File "http/client.py", line 1247, in endheaders
File "http/client.py", line 1026, in _send_output
File "http/client.py", line 966, in send
File "docker/transport/unixconn.py", line 43, in connect
PermissionError: [Errno 13] Permission denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "requests/adapters.py", line 449, in send
File "urllib3/connectionpool.py", line 727, in urlopen
File "urllib3/util/retry.py", line 403, in increment
File "urllib3/packages/six.py", line 734, in reraise
File "urllib3/connectionpool.py", line 677, in urlopen
File "urllib3/connectionpool.py", line 392, in _make_request
File "http/client.py", line 1252, in request
File "http/client.py", line 1298, in _send_request
File "http/client.py", line 1247, in endheaders
File "http/client.py", line 1026, in _send_output
File "http/client.py", line 966, in send
File "docker/transport/unixconn.py", line 43, in connect
urllib3.exceptions.ProtocolError: ('Connection aborted.', PermissionError(13, 'Permission denied'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "docker/api/client.py", line 205, in _retrieve_server_version
File "docker/api/daemon.py", line 181, in version
File "docker/utils/decorators.py", line 46, in inner
File "docker/api/client.py", line 228, in _get
File "requests/sessions.py", line 543, in get
File "requests/sessions.py", line 530, in request
File "requests/sessions.py", line 643, in send
File "requests/adapters.py", line 498, in send
requests.exceptions.ConnectionError: ('Connection aborted.', PermissionError(13, 'Permission denied'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "bin/docker-compose", line 3, in <module>
File "compose/cli/main.py", line 67, in main
File "compose/cli/main.py", line 123, in perform_command
File "compose/cli/command.py", line 69, in project_from_options
File "compose/cli/command.py", line 132, in get_project
File "compose/cli/docker_client.py", line 43, in get_client
File "compose/cli/docker_client.py", line 170, in docker_client
File "docker/api/client.py", line 188, in __init__
File "docker/api/client.py", line 213, in _retrieve_server_version
docker.errors.DockerException: Error while fetching server API version: ('Connection aborted.', PermissionError(13, 'Permission denied'))
[1656] Failed to execute script docker-compose
次はこのエラーについて対応する。
参考
Win版Docker Desktop「The command 'docker' could not be found in this WSL 2 distro.」の対処法
大量のパーミッションエラーへの対処
パーミッションエラーなので、前にsudo
をつけて実行する。
sudo docker-compose exec web rake db:migrate RAILS_ENV=production
masa@DESKTOP-0CNPS43:~/RailsTutorial$ sudo docker-compose exec web rake db:migrate RAILS_ENV=production
I, [2021-01-03T06:20:46.046464 #20] INFO -- : Raven 3.1.1 configured not to capture errors: DSN not set
INFOが出たが、これはエラーではないので、無視して作業を続ける。
(INFO DEBUG WARN ERROR CRITICALというレベルがあり、WARN以上だけに対応すればOK)
参考
heroku - 本番環境のマイグレーションでエラー発生
参考サイト「heroku - 本番環境のマイグレーション」までの手順は問題なく完了したが、"heroku run bundle exec rake RAILS_ENV=production db:migrate
"を実行。
すると、エラー"bash: bundle: command not found
"が出てきた。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ heroku run bundle exec rake RAILS_ENV=production db:migrate
Running bundle exec rake RAILS_ENV=production db:migrate on ⬢ masa-rails-tutorial-20210103... up, run.6112 (Free)
bash: bundle: command not found
herokuへ入り、ls
で確認すると、ファイルが何もない。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ heroku run bash
Running bash on ⬢ masa-rails-tutorial-20210103... up, run.3888 (Free)
~ $ ls
~ $
そこで、手順を一つ飛ばして、git push heroku master
でheroku環境へgitのファイルをプッシュ。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ git push heroku master
Enumerating objects: 207, done.
Counting objects: 100% (207/207), done.
Delta compression using up to 8 threads
Compressing objects: 100% (151/151), done.
Writing objects: 100% (207/207), 178.87 KiB | 89.43 MiB/s, done.
Total 207 (delta 49), reused 190 (delta 41)
remote: Compressing source files... done.
...(省略)
もう一度ls
でファイルを確認。
masa@DESKTOP-0CNPS43:~/RailsTutorial$ heroku run bash
Running bash on ⬢ masa-rails-tutorial-20210103... up, run.4157 (Free)
~ $ ls
app config.ru Gemfile package.json README.md yarn.lock
app.json db Gemfile.lock postcss.config.js spec
babel.config.js docker-compose.ci.yml lib Procfile storage
bin docker-compose.yml log public tmp
config Dockerfile node_modules Rakefile vendor
~ $
ファイルがある!
ブラウザでアプリを確認!
デプロイできたあああ!!!
とても長い戦いでした。。。
参考サイト
自分の最後の手順を見てもらえればわかりますが、「heroku - 本番環境のマイグレーション」はなくてもデプロイできました。むしろ、何もファイルがないのにマイグレーションはできません。この手順で作業する方はお気を付けください。