我用 Go 创建了一个 Web 服务器,并尝试创建一个 docker 镜像用于学习。当我启动 docker 镜像时,它无法使用“docker run”检测到任何环境变量,但如果我启动“docker compose”,我可以看到它们被填充了,我错过了什么?我不明白
主要步骤:
func init() {
fmt.Println("Inizializziamo...")
cmd := exec.Command("env")
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
// Print the output
fmt.Println(string(stdout))
}
docker-compose.yml
services:
blog:
build: .
ports:
- "8080:8080"
environment:
- DB_HOST=db
- DB_PORT=5432
- DB_USER=test_user
- DB_PASSWORD=psw
- DB_NAME=mydb
- PORT=8080
depends_on:
- db
db:
image: postgres:15
restart: always
environment:
- POSTGRES_USER=test_user
- POSTGRES_PASSWORD=psw
- POSTGRES_DB=mydb
ports:
- "5432:5432"
volumes:
- db-data:/var/lib/postgresql/data
volumes:
db-data:
# docker compose run --rm blog env
[+] Creating 1/0
✔ Container mywebserver-db-1 Running 0.0s
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=154d98c6277d
TERM=xterm
DB_PASSWORD=psw
DB_NAME=mydb
PORT=8080
DB_HOST=db
DB_PORT=5432
DB_USER=test_user
HOME=/root
使用 docker run 时无需环境变量
# docker run xxxx/mywebserver
Inizializziamo...
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOSTNAME=0f42e93ff038
HOME=/root
我做错了吗?谢谢你的帮助