High level- i have front end web application which runs on one docker container and i made second container for database mysql.
I picked a environment variable mysqldb
i need to set that variable to ip address of Docker MySQL container. Part two- i got web application which has to know what ip address is running on( mysql container whatever its going to be because the ip of the container will change) so it has to read that environment variable that was set. So my question do i set a variable so when i run the program mysql container runs and shows that database i set up is working
Dockerfile
FROM golang:1.19-bullseye AS build
WORKDIR /app
COPY ./ ./
RUN go build -o main ./
FROM debian:bullseye
COPY --from=build /app/main /usr/local/bin/main
#CMD[apt-get install mysql-clientmy]
CMD ["/usr/local/bin/main"]
makefile
build:
go build -o bin/main main.go
run:
go run main.go
runcontainer:
docker run -d -p 9008:8080 tiny
compile:
echo "Compiling for every OS and Platform"
GOOS=linux GOARCH=arm go build -o bin/main-linux-arm main.go
GOOS=linux GOARCH=arm64 go build -o bin/main-linux-arm64 main.go
GOOS=freebsd GOARCH=386 go build -o bin/main-freebsd-386 main.go
part of my go program
func main() {
linkList = map[string]string{}
http.HandleFunc("/link", addLink)
http.HandleFunc("/hpe/", getLink)
http.HandleFunc("/", Home)
ip := flag.String("i", "0.0.0.0", "")
port := flag.String("p", "8080", "")
flag.Parse()
fmt.Printf("Listening on %s n", net.JoinHostPort(*ip, *port))
log.Fatal(http.ListenAndServe(net.JoinHostPort(*ip, *port), nil))
}
2
Answers
Yes, you can achieved this by using env variable in Dockerfile or Docker compose file. By the way don’t use IP of db container. Always use hostname. Hostname is static but every recreation of container IP will be get changed.
You can do it the following way in the Dockerfile itself(The example itself if from the Docker documentation):
In case of a Docker-compose file, you can try to do the following:
You should change it according to your requirements.
Addendum
:As far as I can understand what you’re trying to achieve, and you can solve this problem by using a
db_env
in your go program structure as well as your docker-compose file.Try to do the following:
HOST=172.0.0.1
viper
or simply usingos.Getenv("HOST")
create a docker-compose file and add both the services you’re supposed to create.
You can look at the example that I provided earlier and then create services accordingly by specifying the same
db_env
below the docker-composeenv_file
flag.