-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

Ben Schreiber
  • 167
  • 1
  • 1
  • 8

1 Answers1

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.

jabbson
  • 4,390
  • 1
  • 13
  • 23
  • This fixed the issue! However, I now cannot connect to the specific database, I updated the error – Ben Schreiber Oct 28 '21 at 22:10
  • The DB with the name "puapp" - does it exist? – jabbson Oct 28 '21 at 22:16
  • 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](https://hub.docker.com/_/mysql) for details (under Environment Variables). – jabbson Oct 28 '21 at 22:19
  • 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. – Ben Schreiber Oct 28 '21 at 22:20
  • 1
    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?.. – jabbson Oct 28 '21 at 22:27
  • https://stackoverflow.com/questions/38504257/mysql-scripts-in-docker-entrypoint-initdb-are-not-executed/52715521 makes some suggestsion on using the initdb directory: "If the mysql data volume exists, it will not be overwritten by the SQLs in the entry db" – erik258 Oct 28 '21 at 23:41