ミニマムにやっておかないと忘れがちなのでメモ
サンプル用Goサーバを作成する
package main
import (
"encoding/json"
"net/http"
)
type User struct {
FirstName string `json:"firstName"`
LastName string `json:"lastName"`
}
func users(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
user := User{
FirstName: "John",
LastName: "Doe",
}
var users []User
users = append(users, user)
json.NewEncoder(w).Encode(users)
}
func main() {
http.HandleFunc("/users", users)
http.ListenAndServe(":8002",nil)
}
普通に起動して動作確認をします。
$ go run main.go
http://localhost:8002/users
にアクセスするとJSON
結果が出力されます。
[
{
"firstName": "John",
"lastName": "Doe"
}
]
Dockerfile
Dockerfileを作成します。alpine
をつけるとよりミニマムなイメージができます。参考(https://hub.docker.com/_/golang?tab=description)
FROMgolang:1.14
#FROMgolang:1.14-alpine
# コンテナログイン時のディレクトリ指定
WORKDIR /opt/sandbox-docker-go
# ホストのファイルをコンテナの作業ディレクトリにコピー
COPY . .
# ADD . .
# ビルド
RUN go build -o app main.go
# 起動
CMD ["/opt/sandbox-docker-go/app"]
構成
$ tree
.
├── Dockerfile
└── main.go
ビルド
$ docker build -t sandbox-docker-go .
[+] Building 3.0s (9/9) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 361B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/golang:1.14 1.8s
=> [1/4] FROM docker.io/library/golang:1.14@sha256:d31a307a7e42116adb00d8d70971dbf228460904dd9b6217e911d088aa4b650c 0.0s
=> [internal] load build context 0.0s
=> => transferring context: 605B 0.0s
=> CACHED [2/4] WORKDIR /opt/sandbox-docker-go 0.0s
=> [3/4] COPY . . 0.0s
=> [4/4] RUN go build -o app main.go 1.0s
=> exporting to image 0.1s
=> => exporting layers 0.1s
=> => writing image sha256:b59f0afdb5a50873182e88aa7e65836b15049b8a8e3d8a3644a856cc438e3610 0.0s
=> => naming to docker.io/library/sandbox-docker-go
Dockerイメージが作成されました。
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
sandbox-docker-go latest b59f0afdb5a5 30 seconds ago 817MB
コンテナ起動
$ docker run -p 8002:8002 -td --name sandbox-docker-go b59f0afdb5a5<br>8fe6ad253218c6c700eb91f458eed99cc8bfbd0ea03423d21a6a42d851268409
プロセスチェック
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUSPORTS NAMES
8fe6ad253218 b59f0afdb5a5 "/opt/sandbox-docker…" 26 seconds ago Up 26 seconds infallible_williams
http://localhost:8002/users
にアクセスして動作確認をします。
[
{
"firstName": "John",
"lastName": "Doe"
}
]
コンテナ再起動
$ docker restart cb8f814837cf
コンテナ停止
$ docker stop cb8f814837cf
コンテナ起動
$ docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUSPORTS NAMES
cb8f814837cf b59f0afdb5a5 "/opt/sandbox-docker…" 3 minutes ago Exited (2) 52 seconds ago reverent_snyder
$ docker start cb8f814837cf
コンテナプロセスkill
$ docker kill cb8f814837cf
コンテナ削除
$ docker rm cb8f814837cf
イメージ削除
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
sandbox-docker-go latest b59f0afdb5a5 13 minutes ago 817MB
$ dockerrmi b59f0afdb5a5