Seeding Postgres database and connect to Node

nodejs
docker
postgresql
circle.yml

#1

I need to seed a Postgres DB and connect my Node server to it. This is the config.yml I’m using.

version: 2
jobs:
  build:
    working_directory: ~/app
    docker:
      - image: circleci/node:7.10
        environment:
          NODE_ENV: development
        # PORT: 4000
          PG_HOST: 127.0.0.1
          POSTGRES_DB: postgres_db
          POSTGRES_USER: postgres
          PG_PASSWD: boilerplate
          JWT_SECRET: 0a65344d-d6fb-47nu-c72p-8456f976ve0q
      - image: circleci/postgres:9.6.2-alpine
        environment:
          POSTGRES_DB: postgres_db
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: boilerplate

    steps:
      - checkout
      - restore_cache:
          key: dependency-cache-{{ checksum "package.json" }}
      - run: npm install
      - save_cache:
          key: dependency-cache-{{ checksum "package.json" }}
          paths:
            - node_modules

      - run:
          name: Wait for db
          command: dockerize -wait tcp://localhost:5432 -timeout 1m

      #- run: echo '/usr/lib/postgresql/9.6/bin/:$PATH' >> $BASH_ENV

      - run: sudo apt install postgresql-client

      #- run: sudo psql postgres --version
      - run: yarn test

I have a CreateDatabase.sql which creates all the tables and seeds the db. How do I run it in the postgres container? I’m also not sure if the Node and postgres connection works.


#2

A late reply but I just spent a lot of time myself trying to get this to work.

If you use a docker image, you’ll need apk instead of sudo apt

  - run:
      name: install postgresql-client
      command: |
        apk update
        apk add postgresql-client

You cannot pass the password as a command line parameter, the easiest option is to set it as a environment variable.
You have to explicitly define the host, otherwise it’ll try to connect via a socket file which is not there because it’s inside docker.

  - run:
      name: create database
      command: |
        set PGPASSWORD=boilerplate
        psql --host localhost -U postgres -d postgres_db < .circleci/CreateDatabase.sql

#3