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?

More than 1 year has passed since last update.

php laravelをdockerで立てるとdbに接続できない

Last updated at Posted at 2023-06-13

はじめに

今回とあるハッカソンに出るにあたってphpを用いたAPIサーバーが必要になった。
それの構築中に起きた問題である。

環境構築

まずはcomposerをインストール

brew install composer

次にcomposerを用いてlaravelの雛形を作成する

composer create-project laravel/laravel --prefer-dist hoge

これでhogeディレクトリ配下に雛形が作成される。

次にhogeディレクトリ配下の.envファイルを編集してデータベース接続の設定をする。

hoge/.env
~~~~~
DB_CONNECTION=pgsql
DB_HOST=db
DB_PORT=5432
DB_DATABASE=test
DB_USERNAME=user
DB_PASSWORD=password
~~~

実行

これでhogeディレクトリ配下で
php artisan serve
するとサーバーが起動する。
この時点でデータベースはポート番号:5432で起動しており、テストデータが入っていることもadminerにより確認できている

また
curl localhost:8000/api/users
でユーザー一覧が取得できるように実装済みで、データが取得できることも確認できた。

問題

今回api開発するにあたってdockerを使う必要が出てきた。
てことで以下のようにDockerfiledocker-compose.ymlを追加した

hoge/Dockerfile
FROM bitnami/laravel
RUN mkdir -p /app
COPY . /app
WORKDIR /app


CMD [ "php", "artisan", "serve","--host=0.0.0.0" ]
docker-compose.yml
#====================
    db:
        container_name: mosa-db
        image: postgres:14
        volumes:
          - dbdata:/var/lib/postgresql/data/
          - ./db/init:/docker-entrypoint-initdb.d
        env_file:
          - .env
        ports:
          - "5432:5432"
    hoge:
        build:
            context: ./hoge
            dockerfile: Dockerfile
        container_name: hoge-php
        ports:
          - '50000:8000'
        volumes:
          - ./hoge:/app
#====================

以下コマンドを実行することで起動できる
docker compose up --build hoge db

起動が確認できたので以下コマンドを実行
curl localhost:8000/api/users

が、しかしなっがいエラー文が返されたので
curl localhost:8000/api/users > hoge.html

hoge.htmlの中身
スクリーンショット 2023-06-13 13.03.08.png

データベースに接続できていない

docker的な問題かと思い、接続文字列をクラウドデータベースに変更してもエラーの内容は変わらなかった

現在解決方法を模索中
分かり次第追記します。

また同じような事例があって解決方法がわかる方がいらっしゃれば教えていただければ幸いです。

追記

こちら結果といたしまして、dockerのネットワークの問題であると推測されました。
解決方法としては

ローカルから踏み台経由で外部DBにアクセスする

こちらが考えられます。

今回作るプロダクトにはそってないと考えた結果、dockerの使用をやめ、vps上に環境を構築しました。

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?