I’m trying to connect MySQL with golang using docker, for local MySQL instance it’s working perfectly but
when trying to access docker container mysql instance, always getting connection refused.
Can anyone help me to solve this issue?
.env
MYSQL_IDS_USERNAME=root
MYSQL_IDS_PASSWORD=12345678
MYSQL_IDS_HOST=localhost
MYSQL_IDS_PORT=3306
MYSQL_IDS_SCHEMA=ids_db
MYSQL_ROOT_PASSWORD=12345678
docker-compose.yml
version: '3.7'
services:
mysql:
image: mysql:latest
volumes:
- "./db_data:/var/lib/mysql"
env_file:
- ".env"
ports:
- "3307:3306"
networks:
- appmysql
id_service:
container_name: id_service
build:
context: .
dockerfile: Dockerfile
image: rezwanulhaque/id-service:latest
volumes:
- "./logs:/app/lib/logs"
ports:
- "7001:7001"
depends_on:
- mysql
networks:
- appmysql
networks:
appmysql:
driver: bridge
Dockerfile
# Start from golang base image
FROM golang:1.14-alpine3.11 AS builder
#ENV GO111MODULE=on
# Add Maintainer info
LABEL maintainer="Rezwanul Haque <rezwanul.cse@gmail.com>"
# Install git.
# Git is required for fetching the dependencies.
RUN apk update && apk add --no-cache git
# Configure the repo url
ENV REPO_URL=github.com/Rezwanul-Haque/ID-Service
# Setup our $GOPATH
ENV GOPATH=/app
# Set the current working directory inside the container
ENV APP_PATH=$GOPATH/src/$REPO_URL
ENV WORKPATH=$APP_PATH/src/
COPY src $WORKPATH
WORKDIR $WORKPATH
# Copy go mod and sum files
#COPY go.mod .
#COPY go.sum .
# Download all dependencies. Dependencies will be cached if the go.mod and the go.sum files are not changed
RUN go mod download
# Build the Go app
RUN CGO_ENABLED=0 GOOS=linux go build -o id-service .
# Start a new stage from scratch
#FROM alpine:latest
#
#RUN ls bin/
## Copy the Pre-built binary file from the previous stage. Observe we also copied the .env file
#COPY --from=builder /app/id-service .
#COPY --from=builder /app/.env .
#
# Expose port 7001 to the outside world
EXPOSE 7001
# Command to run the executable
ENTRYPOINT ["./id-service"]
db.go
var (
Client *sql.DB
username = os.Getenv("MYSQL_IDS_USERNAME")
password = os.Getenv("MYSQL_IDS_PASSWORD")
host = os.Getenv("MYSQL_IDS_HOST")
port = os.Getenv("MYSQL_IDS_PORT")
schema = os.Getenv("MYSQL_IDS_SCHEMA")
)
func init() {
dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8",
username, password, host, port, schema,
)
var err error
Client, err = sql.Open("mysql", dataSourceName)
if err != nil {
logger.Error("connecting to database failed: ", err)
panic(err)
}
if err = Client.Ping(); err != nil {
panic(err)
}
logger.Info("database successfully configured")
}