docker 踩坑笔记之 psql: could not connect to server

Posted 天师符

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了docker 踩坑笔记之 psql: could not connect to server相关的知识,希望对你有一定的参考价值。

最近在用docker跑rails,也遇到了一些坑,这里记录一下。

首先build项目:

docker-compose build

然后就开始报错了:

psql: 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"?

这里报错是说找不到 /var/run/postgresql/.s.PGSQL.5432 文件,但我本地运行是没问题的。于是去找docker从入门到实践这本书的docker rails 例子, 地址在这里:发现我的database.yml文件不对。我的是这样的:

default: &default
  adapter: postgresql
  encoding: unicode`请输入代码`
  # For details on connection pooling,www.97yingyuan.org see Rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

Rails 默认读取的数据库目标是 localhost ,我们需要手动指定容器的 db 。同样的,还需要把用户名修改成和 postgres 镜像预定的一致。 打开最新生成的 database.yml 文件。用以下内容替换:

default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  username: postgres
  host: db

这样再运行docker-compose build,成功build! 然后再跑起来docker-compose up,悲剧的又报错了:

ActiveRecord::NoDatabaseError (FATAL: database "heroku_app_development" does not exist

提示没有创建heroku_app_development数据库,OK,那就创建一个:

sudo docker ps #列出所有容器
sudo docker exec -it [container ID] /bin/bash #进入postgres
sudo su - postgres #切换到postgres用户,因为这个用户有createdb权限
ceratedb heroku_app_development #heroku_app_development 创建完成!

再运行docker-compose up,又报错:

Migrations are pending. To resolve this issue, run:

    bin/rails db:migrate RAILS_ENV=development

railser应该很熟悉,数据库迁移,进入web容器:
sudo docker exec -it [container ID] /bin/bash #进入web容器
rails db:migrate #迁移成功!








以上是关于docker 踩坑笔记之 psql: could not connect to server的主要内容,如果未能解决你的问题,请参考以下文章

问题解决:psql: could not connect to server: No such file or directory Is the server running locally and

docker+nginx 踩坑之路

flutter踩坑01:下载包失败:Could not resolve all artifacts for configuration....

JDK源码笔记之Integer深度解析以及并发下错误的加锁方式踩坑笔记

博客项目踩坑-Could not write JSON: Infinite recursion (StackOverflowError)

博客项目踩坑-Could not write JSON: Infinite recursion (StackOverflowError)