-1

I'm very new to Docker, and I'm trying to dockerize a Go REST API and MySQL database to communicate with each other using Docker Compose. I am getting the error [main] Error 1049: Unknown database 'puapp'

Docker compose:

version: '3'
services:
  db:
    build: ./mysql/ 
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    volumes:
      - db_volume:/var/lib/mysql

  api-service:
    restart: always
    build: ./
    ports:
      - "8080:80"
    environment:
      - DB_USER=root
      - DB_PASS=root
      - DB_ADDRESS=db:3306
      - DB_PROTOCOL=tcp
      - DB_NAME=puapp
    depends_on:
      - db
    links:
      - db

volumes:
  db_volume:

Dockerfile for go service:

# syntax=docker/dockerfile:1

# Build stage
FROM golang:1.16-alpine AS builder
WORKDIR /app
COPY . .
RUN go mod download
WORKDIR /app/src/main
RUN go build -o restserv


# Run stage
FROM alpine:3.13
WORKDIR /app
COPY --from=builder /app/src/main/restserv .
EXPOSE 8080

CMD "./restserv"

Dockerfile for MySQL:

FROM mysql:latest
ADD dump.sql /docker-entrypoint-initdb.d

enter image description here

enter image description here

Full code - https://github.com/bens-schreiber/restservproj Let me know if I need to add anything

1
  • 2
    have You tried to write: DB_ADDRESS=db:3306 ? Commented Oct 28, 2021 at 21:28

1 Answer 1

1

Containers will be having their own ip addresses, so API container won't be able to access mysql container over 127.0.0.1. As mentioned in the comments, you want to utilize container's names to addresses from container from another. See this page for details.

Sign up to request clarification or add additional context in comments.

6 Comments

This fixed the issue! However, I now cannot connect to the specific database, I updated the error
The DB with the name "puapp" - does it exist?
If it doesn't you can set to create a default db with this name by passing another ENV variable MYSQL_DATABASE. See this page for details (under Environment Variables).
It should exist, in my MySQL file I create the database via my dump.sql. When I go into the container, I can go into mysql and see that the database is there. So I am not sure.
Could you add the output of show databases; and specify where you are getting this error exactly? When starting the container or from Go code?..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.