i wrote a basic api with typescript in nodejs which runs fine when started with the start script “node dist/index.js”, but after dockerizing it, the database seems to have been connected although there are no tables accessible
server logs
[7/10/2024, 1:26:07 PM] [INFO] [0] [index.ts] Server is running on http://localhost:3000
[7/10/2024, 1:26:13 PM] [INFO] [0] [db.config] Connected to the db
[7/10/2024, 1:26:13 PM] [ERROR] [0] [operator.signup.controller] error: relation "operators" does not exist
at /app/node_modules/pg-pool/index.js:45:11
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
length: 108,
severity: 'ERROR',
code: '42P01',
detail: undefined,
hint: undefined,
position: '13',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'parse_relation.c',
line: '1392',
routine: 'parserOpenTable'
}
but when i logged in to docker container and connected to pg, the tables actually do exist.
docker container for pg database
github – https://github.com/aditipolkam/quicktrip
Dockerfile – using docker multi-stage build
# Stage 1: PostgreSQL
FROM postgres:15.5 AS db
COPY init.sql /docker-entrypoint-initdb.d/
EXPOSE 5432
# Stage 2: Node.js build
FROM node:20.5 AS build
WORKDIR /app
COPY package*.json .
RUN npm install
COPY . .
RUN npm run build
# Stage 3: Node.js production
FROM node:20.5 AS production
WORKDIR /app
COPY ssl-tls-key.pem ssl-tls-key.pem
COPY package*.json .
RUN npm install --only=production
ARG NODE_ENV
COPY .env.${NODE_ENV} .env
COPY --from=build /app/dist ./dist
CMD ["node", "dist/index.js"]
docker-compose.yml
services:
db:
build:
context: .
target: db
env_file:
- .env.${NODE_ENV}
ports:
- "5432:5432"
volumes:
- db_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER}"]
interval: 30s
timeout: 10s
retries: 5
app:
build:
context: .
target: production
args:
NODE_ENV: ${NODE_ENV}
depends_on:
- db
ports:
- "3000:3000"
env_file:
- .env.${NODE_ENV}
environment:
- NODE_ENV=${NODE_ENV}
volumes:
db_data:
init.sql
CREATE TABLE test_table (
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE operators (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
contact INT NOT NULL,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
);
build and start docker containers – NODE_ENV=local docker-compose up --build -d
NODE_ENV can change – local | staging
.env.local
POSTGRES_USER=postgres
POSTGRES_HOST=db #was localhost earlier but changed to db for docker container execution
POSTGRES_PASSWORD=postgresdb
POSTGRES_DB=quicktrip
POSTGRES_PORT=5432
SALT_ROUNDS=10
Aditi Polkam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.