goko-.build

Adding files to image built with ko build


I have a go application that is being containerized via ko build. This is the ko build command im using to build my image:

ko build ./cmd/webserver \
    --platform=linux/amd64,linux/arm64,linux/arm/v8 \
    --tags=latest \
    --bare \
    --local

I have migrations files that i run (using golang-migrations). I want the migrations to run everytime the container starts so they need to be available in the container FS. I can't seem to find a way with ko build to add the migrations folder to the image no matter the location of the migrations folder in my project.

Option 1:

my-app/
├── cmd/
│   └── webserver/
│       ├── main.go
│       └── migrations/
│             ├── 001-migrations.up.sql
│             └── 001-migrations.down.sql
├── .ko.yaml
└── Makefile

Option 2:

my-app/
├── cmd/
│   └── webserver/
│       └── main.go
├── migrations/
│   ├── 001-migrations.up.sql
│   └── 001-migrations.down.sql
└── Makefile

Is there any way to achieve this with ko build?


Solution

  • ko only copies your Go binary. To include static files you need to use kodata/. Anything under <importpath>/kodata gets bundled into the image and mounted at $KO_DATA_PATH.

    For example:

    cmd/webserver/
      main.go
      kodata/
        migrations/
          001.up.sql
          001.down.sql
    

    At runtime you can read them from the path given by the KO_DATA_PATH environment variable

    like

    root := os.Getenv("KO_DATA_PATH")
    mPath := filepath.Join(root, "migrations")
    m, _ := migrate.New("file://"+mPath, dbURL)
    m.Up()
    

    doc