我通過 docker-compose 使用 postgres 部署了一個 gorm 應(yīng)用程序。我通過另一個容器服務(wù)進(jìn)行了數(shù)據(jù)庫創(chuàng)建和數(shù)據(jù)遷移。此處僅列出了應(yīng)用和數(shù)據(jù)庫容器問題。docker-compose.yml app: build: ./app command: ["/bin/wait-for-it.sh", "db:5432", "--", "/bin/main"] volumes: - ./app/:/app/ ports: - 8080:8080 environment: - DB_USER=postgres - DB_NAME=mydb - DB_PASS=password depends_on: - db links: - db db: image: postgres:13-alpine environment: - POSTGRES_PASSWORD=password - POSTGRES_DB=mydbDockerfileFROM golang:1.16.3-alpine3.13 AS builderWORKDIR /appCOPY . .RUN CGO_ENABLED=0 GOOS=linux go build -o mainFROM alpine:3.13RUN apk update && apk --no-cache add bashCOPY --from=builder /app /bin/.RUN ["chmod", "+x", "/bin/wait-for-it.sh"]db/db.gopackage dbimport ( "fmt" "os" "gorm.io/driver/postgres" "gorm.io/gorm")var ( db *gorm.DB)func Init() { conn := fmt.Sprintf("host=db port=5432 user=%s password=%s dbname=%s sslmode=disable", os.Getenv("DB_USER"), os.Getenv("DB_PASS"), os.Getenv("DB_NAME")) _, err := gorm.Open(postgres.Open(conn), &gorm.Config{}) if err != nil { panic(err) }}func GetDB() *gorm.DB { return db}models/post.gopackage modelstype Post struct { ID int `json:"id" gorm:"primary_key"` Title string `json:"title"` Body string `json:"body"`}main.go 1 │ package main 2 │ 3 │ import ( 4 │ "app/db" 5 │ "app/models" 6 │ "fmt" 7 │ ) 8 │ 9 │ func main() { 10 │ db.Init() 11 │ 12 │ db := db.GetDB() 13 │ 14 │ var posts []models.Post 15 │ db.Find(&posts) 16 │ fmt.Println(posts) 17 │ }
- 1 回答
- 0 關(guān)注
- 103 瀏覽
添加回答
舉報
0/150
提交
取消