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
#进入postgressudo 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
#迁移成功!