3
0

docker initでDocker環境構築

Posted at

docker initGodockerfikleを作って、中身を確認してみよう:eyes:

docker init

対話形式で設定を決めていくスタイルなので、オプションを覚えなくても使えそう

PS C:\Users\xxx\Documents\go-app> docker init

Welcome to the Docker Init CLI!

This utility will walk you through creating the following files with sensible defaults for your project:
  - .dockerignore
  - Dockerfile
  - compose.yaml
  - README.Docker.md

Let's get started!

? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use?  [Use arrows to move, type to filter]
? What application platform does your project use? Go
? What version of Go do you want to use? 1.22.0-alpine3.19

? What version of Go do you want to use? 1.22.0-alpine3.19
? What's the relative directory (with a leading .) of your main package? .

? What's the relative directory (with a leading .) of your main package? .  
? What port does your server listen on? 3333

? What port does your server listen on? 3333

CREATED: .dockerignore
CREATED: Dockerfile
CREATED: compose.yaml
CREATED: README.Docker.md

✔ Your Docker files are ready!

Take a moment to review them and tailor them to your application.

When you're ready, start your application by running: docker compose up --build

Your application will be available at http://localhost:3333

Consult README.Docker.md for more information about using the generated files.

出力物

dockerfile

# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/go/dockerfile-reference/

################################################################################
# Create a stage for building the application.
ARG GO_VERSION=1.22.0-alpine3.19
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION} AS build
WORKDIR /src

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /go/pkg/mod/ to speed up subsequent builds.
# Leverage bind mounts to go.sum and go.mod to avoid having to copy them into
# the container.
RUN --mount=type=cache,target=/go/pkg/mod/ \
    --mount=type=bind,source=go.sum,target=go.sum \
    --mount=type=bind,source=go.mod,target=go.mod \
    go mod download -x

# This is the architecture you’re building for, which is passed in by the builder.
# Placing it here allows the previous steps to be cached across architectures.
ARG TARGETARCH

# Build the application.
# Leverage a cache mount to /go/pkg/mod/ to speed up subsequent builds.
# Leverage a bind mount to the current directory to avoid having to copy the
# source code into the container.
RUN --mount=type=cache,target=/go/pkg/mod/ \
    --mount=type=bind,target=. \
    CGO_ENABLED=0 GOARCH=$TARGETARCH go build -o /bin/server .

################################################################################
# Create a new stage for running the application that contains the minimal
# runtime dependencies for the application. This often uses a different base
# image from the build stage where the necessary files are copied from the build
# stage.
#
# The example below uses the alpine image as the foundation for running the app.
# By specifying the "latest" tag, it will also use whatever happens to be the
# most recent version of that image when you build your Dockerfile. If
# reproducability is important, consider using a versioned tag
# (e.g., alpine:3.17.2) or SHA (e.g., alpine@sha256:c41ab5c992deb4fe7e5da09f67a8804a46bd0592bfdf0b1847dde0e0889d2bff).
FROM alpine:latest AS final

# Install any runtime dependencies that are needed to run your application.
# Leverage a cache mount to /var/cache/apk/ to speed up subsequent builds.
RUN --mount=type=cache,target=/var/cache/apk \
    apk --update add \
        ca-certificates \
        tzdata \
        && \
        update-ca-certificates

# Create a non-privileged user that the app will run under.
# See https://docs.docker.com/go/dockerfile-user-best-practices/
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser
USER appuser

# Copy the executable from the "build" stage.
COPY --from=build /bin/server /bin/

# Expose the port that the application listens on.
EXPOSE 3333

# What the container should run when it is started.
ENTRYPOINT [ "/bin/server" ]

DeepLで日本語にしたもの

# syntax=docker/dockerfile:1

# このファイル全体を通して、使い始めの手助けとなるようなコメントを用意しています。
# さらにヘルプが必要な場合は、以下のDockerfileリファレンスガイドを参照してください。
# https://docs.docker.com/go/dockerfile-reference/

################################################################################
# アプリケーションをビルドするためのステージを作成します。
ARG GO_VERSION=1.22.0-alpine3.19
FROM --platform=$BUILDPLATFORM golang:${GO_VERSION}. build
WORKDIR /src

# Dockerのキャッシュを利用するために、依存関係を別ステップとしてダウンロードする。
# go/pkg/mod/へのキャッシュマウントを活用して、その後のビルドを高速化。
# go.sumとgo.modへのバインドマウントを活用して、 # コンテナにコピーする手間を省く。
# コンテナにコピーする必要がなくなる。
RUN --mount=type=cache,target=/go/pkg/mod/ \
    -mount=type=bind,source=go.sum,target=go.sum \
    --mount=type=bind,source=go.mod,target=go.mod  \
    go mod download -x

# これはビルダーから渡されるビルド対象のアーキテクチャです。
# ここに置くことで、前の手順をアーキテクチャをまたいでキャッシュできるようになります。
ARG TARGETARCH

# アプリケーションをビルドする。
# 以降のビルドを高速化するために、/go/pkg/mod/へのキャッシュマウントを活用する。
# ソースコードをコンテナにコピーする手間を省くために、カレントディレクトリへのバインドマウントを活用する。
# ソースコードをコンテナにコピーする手間を省く。
RUN --mount=type=cache,target=/go/pkg/mod/ \
    --mount=type=bind,target=. \
    CGO_ENABLED=0 GOARCH=$TARGETARCH go build -o /bin/server .

################################################################################
# アプリケーションを実行するための新しいステージを作成する。
# アプリケーションを実行するための新しいステージを作成します。これは多くの場合、ビルドステージとは異なるベース
# 必要なファイルはビルドステージからコピーされます。
# ステージから必要なファイルがコピーされます.
#
# 以下の例では、アプリを実行するための基盤としてalpineイメージを利用しています。
# "latest "タグを指定することで、アプリを実行する際に、そのイメージの最新バージョンが利用されます。
# "latest "タグを指定することで、Dockerfileをビルドする際に、そのイメージの最新バージョンが利用されます。
# もし再現性を重視するのであれば、バージョン指定タグの利用を検討してみてください。
# (例: alpine:3.17.2)やSHA (例: alpine@sha256:c41ab5c992deb4fe7e5da09f67a8804a46bd0592bfdf0b1847dde0e0889d2bff)を使うことを検討してください。
FROM alpine:latest AS final

# アプリケーションを実行するために必要なランタイムの依存関係をインストールします。
# 以降のビルドを高速化するために、/var/cache/apk/へのキャッシュマウントを利用します。
RUN --mount=type=cache,target=/var/cache/apk  \
    apk --update add
        ca-certificates
        tzdata
        && \
        update-ca-certificates

# アプリを実行する非特権ユーザーを作成します。
# https://docs.docker.com/go/dockerfile-user-best-practices/ を参照してください。
ARG UID=10001
RUN adduser \
    --disabled-password \
    --gecos "" \
    --home "/nonexistent" \
    --shell "/sbin/nologin" \
    --no-create-home \
    --uid "${UID}" \
    appuser
USER appuser

# ビルド段階から実行ファイルをコピーする。
COPY --from=build /bin/server /bin/ # アプリケーションがリッスンするポートを公開する。

# アプリケーションがリッスンするポートを公開する。
EXPOSE 3333

# コンテナの起動時に実行する内容を指定する。
ENTRYPOINT [ "/bin/server" ]

compose.yaml

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Docker compose reference guide at
# https://docs.docker.com/go/compose-spec-reference/

# Here the instructions define your application as a service called "server".
# This service is built from the Dockerfile in the current directory.
# You can add other services your application may depend on here, such as a
# database or a cache. For examples, see the Awesome Compose repository:
# https://github.com/docker/awesome-compose
services:
  server:
    build:
      context: .
      target: final
    ports:
      - 3333:3333

# The commented out section below is an example of how to define a PostgreSQL
# database that your application can use. `depends_on` tells Docker Compose to
# start the database before your application. The `db-data` volume persists the
# database data between container restarts. The `db-password` secret is used
# to set the database password. You must create `db/password.txt` and add
# a password of your choosing to it before running `docker compose up`.
#     depends_on:
#       db:
#         condition: service_healthy
#   db:
#     image: postgres
#     restart: always
#     user: postgres
#     secrets:
#       - db-password
#     volumes:
#       - db-data:/var/lib/postgresql/data
#     environment:
#       - POSTGRES_DB=example
#       - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
#     expose:
#       - 5432
#     healthcheck:
#       test: [ "CMD", "pg_isready" ]
#       interval: 10s
#       timeout: 5s
#       retries: 5
# volumes:
#   db-data:
# secrets:
#   db-password:
#     file: db/password.txt

DeepLで日本語にしたもの

# このファイル全体を通して、使い始めの手助けとなるようなコメントを用意しています。
# さらにヘルプが必要な場合は、以下のDocker composeリファレンスガイドを参照してください。
# https://docs.docker.com/go/compose-spec-reference/

# ここでは、アプリケーションを "server "というサービスとして定義します。
# このサービスはカレントディレクトリのDockerfileからビルドされます。
# このサービスは、カレントディレクトリのDockerfileからビルドされます。
# データベースやキャッシュなど、アプリケーションが依存する他のサービスをここに追加することができます。
# データベースやキャッシュのような. 例については、Awesome Composeのリポジトリを参照してください:
# https://github.com/docker/awesome-compose
services:
  server:
    build:
      context: .
      target: final
    ports:
      - 3333:3333

# 以下のコメントアウトされたセクションは、アプリケーションが利用できるPostgreSQLデータベースを定義する方法の例です。
# データベースを定義する方法です。`depends_on`はDocker Composeに次のように指示します。
# アプリケーションの前にデータベースを起動します。`db-data`ボリュームはデータベースのデータを保持します。
# コンテナの再起動時にデータベースのデータを保持する。`db-password` シークレットを使用する。
# データベースのパスワードを設定する。`db/password.txt` を作成し、そこに任意のパスワードを追加する必要がある。
# `docker compose up` を実行する前に `db/password.txt` を作成し、そこに任意のパスワードを追加する必要がある。
#     depends_on:
#       db:
#         condition: service_healthy
#   db:
#     image: postgres
#     restart: always
#     user: postgres
#     secrets:
#       - db-password
#     volumes:
#       - db-data:/var/lib/postgresql/data
#     environment:
#       - POSTGRES_DB=example
#       - POSTGRES_PASSWORD_FILE=/run/secrets/db-password
#     expose:
#       - 5432
#     healthcheck:
#       test: [ "CMD", "pg_isready" ]
#       interval: 10s
#       timeout: 5s
#       retries: 5
# volumes:
#   db-data:
# secrets:
#   db-password:
#     file: db/password.txt

.dockerignore

.dockerignore
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.com/go/build-context-dockerignore/

**/.DS_Store
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md

README.Docker.md

### Building and running your application

When you're ready, start your application by running:
`docker compose up --build`.

Your application will be available at http://localhost:3333.

### Deploying your application to the cloud

First, build your image, e.g.: `docker build -t myapp .`.
If your cloud uses a different CPU architecture than your development
machine (e.g., you are on a Mac M1 and your cloud provider is amd64),
you'll want to build the image for that platform, e.g.:
`docker build --platform=linux/amd64 -t myapp .`.

Then, push it to your registry, e.g. `docker push myregistry.com/myapp`.

Consult Docker's [getting started](https://docs.docker.com/go/get-started-sharing/)
docs for more detail on building and pushing.

### References
* [Docker's Go guide](https://docs.docker.com/language/golang/)

DeepLで日本語にしたもの

### アプリケーションのビルドと実行

準備ができたら、アプリケーションを起動してください:
`docker compose up --build`.

アプリケーションはhttp://localhost:3333。

### アプリケーションをクラウドにデプロイする

まず、イメージをビルドします: docker build -t myapp .`.
クラウドが開発マシンと異なるCPUアーキテクチャを使用している場合
クラウドがあなたの開発マシンと異なるCPUアーキテクチャを使っている場合(例えば、あなたはMac M1を使っていて、クラウドプロバイダーはamd64)、
そのプラットフォーム用にイメージをビルドする必要があります:
docker build --platform=linux/amd64 -t myapp .`.

そして、それをあなたのレジストリにプッシュします、例えば `docker push myregistry.com/myapp`.

Dockerの[getting started](https://docs.docker.com/go/get-started-sharing/)
docsを参照してください。

### 参考文献
* DockerのGoガイド](https://docs.docker.com/language/golang/)

Reference

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0