LoginSignup
0
0

More than 1 year has passed since last update.

sqlxでPostgresql(Docker)に接続するとerror communicating with database: Connection refusedとなる

Posted at

はじめに

以下の書籍をRustのコンテナ上で実行したところDatabase接続につまづいたのでまとめます

問題

書籍の設定をしたところRustコンテナからpostgresqlに接続ができませんでした

$ make dev

error: error communicating with database: Connection refused (os error 111)
make: *** [Makefile:6: dev] Error 1

sqlx create dbで落ちていました

設定方法

まずはdocker-compose.ymlでコンテナ間で通信ができるようにします

docker-compose.yml
version: '3'
services:
  rust:
    build: .
    container_name: rust
    tty: true
    ports:
      - "3000:3000"
    volumes:
      - .:/app
    env_file:
      - .env
    networks:
      - app-net
  database:
    build:
      context: ./database
      dockerfile: Dockerfile
      target: 'database'
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: admin
      POSTGRES_USER: admin
      POSTGRES_DB: todosnetworkName
      TZ: Asia/Tokyo
    restart: always
    networks:
      - app-net
  
volumes:
  pgdata:

networks:
  app-net:
    driver: bridge

ポイントはbrigeを行うことです
これをすることでRustからdatabaseという名前でアクセスしていきます(localhostのような感じで)

次に.envのURLも変更していきます

.env
DATABASE_URL="postgres://admin:admin@database:5432/todos"

次にMakefileも修正します

Makefile
dev:
	sqlx db create
	sqlx migrate run
	cd my-todo && cargo watch -x run

make devを実行したときにmigrateまでしたらmy-todoに移動してcargo runを実行します。これはCargo.toml/my-todoにあるので、実行場所を変えています

次にcargo watchを利用するためにrustのDockerfileを変更します

Dockerfile
FROM rust:alpine3.17

RUN apk update && apk add git alpine-sdk make libffi-dev openssl-dev pkgconfig
RUN rustup component add rls rust-analysis rustfmt clippy
RUN cargo install sqlx-cli cargo-watch

WORKDIR /app/my-todo

cargo-watchをインストールしました

最終的には以下のディレクトリ構成になりました

├ database
    └ Dockerfile (DB用のDockerfile)
├ migrations
    └ timestamp_init.sql
├ my-todo
    └ src
    └ Cargo.toml
    └ Cargo.lock
├ .env
├ docker-compose.yml
├ Dockerfile (Rust用のDockerfile)
├ Makefile

おわりに

コンテナ間で通信を行うのを久しぶりにやったので備忘録を兼ねてまとめてみました

参考

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