I have a mysql database running with the following docker-compose.yml
:
version: '3.3' services: db: image: mysql:5.7 restart: always environment: MYSQL_DATABASE: 'demo' # So you don't have to use root, but you can if you like MYSQL_USER: 'user' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: # <Port exposed> : < MySQL Port running inside container> - '3306:3306' expose: # Opens port 3306 on the container - '3306' # Where our data will be persisted volumes: - my-db:/var/lib/mysql networks: - backendnetworks: backend: driver: bridge# Names our volumevolumes: my-db:
$ docker-compose build
$ docker-compose up
I have a basic golang rest api with the following Dockerfile
:
# Start from golang:1.12-alpine base imageFROM golang:1.12-alpine# Adding git, bash and openssh to the imageRUN apk update && apk upgrade && \ apk add --no-cache bash git openssh# Set the Current Working Directory inside the containerWORKDIR /app# Copy the source from the current directory to the Working Directory inside the containerCOPY . .RUN go get -d github.com/gorilla/muxRUN go get -d github.com/go-sql-driver/mysqlRUN go get -d github.com/golang-migrate/migrateRUN go get -d github.com/golang-migrate/migrate/database/mysqlRUN go get -d github.com/golang-migrate/migrate/source/file# Build the Go appRUN go build -o main .# Expose port 8080 to the outside worldEXPOSE 8080# Run the executableCMD ["./main"]
and the following function is called:
func CreateDatabase() (*sql.DB, error) { serverName := "localhost:3306" user := "user" password := "password" dbName := "demo" connectionString := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&collation=utf8mb4_unicode_ci&parseTime=true&multiStatements=true", user, password, serverName, dbName) db, err := sql.Open("mysql", connectionString) if err != nil { return nil, err } if err := migrateDatabase(db); err != nil { return db, err } return db, nil}
$ docker run -p 80:8080 --network=<appname>-mysql_backend <imageid>
$ Database connection failed: %sdial tcp 127.0.0.1:3306: connect: connection refused
I cannot get the api to establish a database connection with the database container?