首页 > 解决方案 > Docker-compose 无法翻译主机名“postgres”

问题描述

我对 Docker 还很陌生。当我运行时docker-compose up,我会收到以下错误。

PG::ConnectionBad
could not translate host name "postgres" to address: Name does not resolve

在日志中,它说以下内容

postgres_1   | The database cluster will be initialized with locale "C".
postgres_1   | The default database encoding has accordingly been set to "SQL_ASCII".
postgres_1   | The default text search configuration will be set to "english".
postgres_1   | 
postgres_1   | Data page checksums are disabled.
postgres_1   | 
postgres_1   | initdb: directory "/var/lib/postgresql/data" exists but is not empty
postgres_1   | If you want to create a new database system, either remove or empty
postgres_1   | the directory "/var/lib/postgresql/data" or run initdb
postgres_1   | with an argument other than "/var/lib/postgresql/data".

这是我的 docker-compose 设置。

# docker-compose.yml

version: '3'
services:
  postgres:
    image: postgres:9.6-alpine
    volumes:
      - postgresql-data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
  app:
    build:
      context: .
    command: "bundle exec rails server -b 0.0.0.0"
    ports:
      - "3020:3000"
    depends_on:
      - postgres
volumes:
  postgresql-data:
# Dockerfile

FROM ruby:2.3.7-alpine

ENV LANG C.UTF-8
ENV RAILS_ENV=development

RUN apk add --update --no-cache --virtual=builders \
      alpine-sdk build-base linux-headers ruby-dev zlib-dev postgresql-dev
RUN apk add --update --no-cache \
      libc6-compat libc-dev zlib ruby-json tzdata yaml less curl postgresql
RUN mkdir /app

WORKDIR /app

COPY Gemfile /app/Gemfile
COPY Gemfile.lock /app/Gemfile.lock
RUN bundle install
COPY . /app
# database.yml
default: &default
  adapter: postgresql
  encoding: utf8
  host: postgres
  username: postgres
  password: 
  port: 5432

development:
  <<: *default
  template: template0
  database: todo_development

我在这里做错了什么?

如果我在我的 中host从更改postgres为,我会收到以下错误。localhostdatabase.yml

Connection refused Is the server running on host “localhost” (127.0.0.1)

标签: ruby-on-railspostgresqldockerdocker-compose

解决方案


推荐阅读