LoginSignup
7
9

More than 5 years have passed since last update.

Docker-composeでappとDBの接続する際の注意点

Last updated at Posted at 2018-07-22

Docker composeでappとDBを接続するときは、appのソースコード内で指定するDBのホスト名をDBのコンテナを作成するときのサービス名にする。

例えばdocker-compose.ymlをこのようにしたら

docker-compose.yml
nodeapp:
  image: node:8.9.4
  container_name: node-dev
  tty: true
  volumes:
    - ./node/src:/src
  ports:
    - "8080:8000"
  links:
    - postgresql

postgresql:
  image: postgres
  environment:
    POSTGRES_USER: postgres
    POSTGRES_PASSWORD: postgres
    POSTGRES_DB: dbname
  ports:
    - "5432:5432"
  volumes:
    - postgresql.volume:/var/lib/postgresql/data
  container_name: postgres-db

host名はpostgresqlとなるので、
DBに接続する際は、以下のソースコードの4行目のようにpostgresqlをホスト名とする。

post.js
'use strict';
const Sequelize = require('sequelize');
const sequelize = new Sequelize(
    'postgres://postgres:postgres@postgresql/dbname',
    {logging: false });
const Post = sequelize.define('Post', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    content: {
        type: Sequelize.TEXT
    },
    postedBy: {
        type: Sequelize.STRING
    },
    trackingCookie: {
        type: Sequelize.STRING
    }
}, {
    freezeTableName: true,
    timestamps: true
});

Post.sync();
module.exports = Post;

参考

7
9
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
7
9