Fixing PostgreSQL Connection Errors in Rails CI

· CI/CD & GitHub Actions · By Zeeshan Ahmad

Fixing PostgreSQL Connection Error in Rails CI/CD

Understanding the Problem

The error you're seeing (PG::ConnectionBad: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory) typically indicates that Rails is attempting to connect to PostgreSQL via a Unix socket but cannot find the server running on that socket. Since you're running PostgreSQL inside a Docker container in GitHub Actions, the problem is likely due to a mismatch between the expected connection type (socket vs. TCP/IP).

Solution Steps

1. Update config/database.yml

Ensure the test environment is configured to use TCP/IP:

bash
test:
  <<: *default
  database: myapp_test
  username: postgres
  password: postgres
  host: localhost
  port: 5432

2. Configure PostgreSQL in GitHub Actions

In your CI workflow file, define the PostgreSQL service:

bash
services:
  postgres:
    image: postgres:13
    ports:
      - 5432:5432
    options: --health-cmd "pg_isready -U postgres" --health-interval 10s --health-timeout 5s --health-retries 5
    env:
      POSTGRES_PASSWORD: postgres
      POSTGRES_USER: postgres
      POSTGRES_DB: myapp_test

3. Initialize the Database

Ensure the database is initialized before running tests:

bash
bin/rails db:create db:schema:load db:fixtures:load

4. Check PostgreSQL Logs

If PostgreSQL still fails to connect, check the container logs for issues:

bash
docker logs 

Conclusion

By ensuring the database configuration uses TCP/IP, setting up the PostgreSQL service in CI correctly, and initializing the database, you can resolve the connection issue. If problems persist, check logs and verify the health of the PostgreSQL service.

Related articles

Home · All Tools · Blog