Help us understand the problem. What is going on with this article?

Phoenix on Kubernetesでpostgresでは無くMySQLを使う時のメモ

はじめに

以下の記事でPhoenix on Kubernetes with postgresの環境は整えることができます。
【Elixir / Phoenix】初心者が流れで学ぶDocker/Kubernetes超入門

この記事では上の記事の環境をMySQLで動くように変更してみます。

適当にアプリを作る

$ mix phx.new . --app dododo --database=mysql
The directory /Users/nakatakensei/docker-elixir already exists. Are you sure you want to continue? [Yn] y
* creating config/config.exs
* creating config/dev.exs
* creating config/prod.exs
* creating config/prod.secret.exs
* creating config/test.exs
* creating lib/dododo/application.ex
* creating lib/dododo.ex
* creating lib/dododo_web/channels/user_socket.ex
* creating lib/dododo_web/views/error_helpers.ex
* creating lib/dododo_web/views/error_view.ex
* creating lib/dododo_web/endpoint.ex
* creating lib/dododo_web/router.ex
* creating lib/dododo_web.ex
* creating mix.exs
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating test/support/channel_case.ex
* creating test/support/conn_case.ex
* creating test/test_helper.exs
* creating test/dododo_web/views/error_view_test.exs
* creating lib/dododo/repo.ex
* creating priv/repo/migrations/.formatter.exs
* creating priv/repo/seeds.exs
* creating test/support/data_case.ex
* creating lib/dododo_web/controllers/page_controller.ex
* creating lib/dododo_web/templates/layout/app.html.eex
* creating lib/dododo_web/templates/page/index.html.eex
* creating lib/dododo_web/views/layout_view.ex
* creating lib/dododo_web/views/page_view.ex
* creating test/dododo_web/controllers/page_controller_test.exs
* creating test/dododo_web/views/layout_view_test.exs
* creating test/dododo_web/views/page_view_test.exs
* creating lib/dododo_web/gettext.ex
* creating priv/gettext/en/LC_MESSAGES/errors.po
* creating priv/gettext/errors.pot
* creating assets/webpack.config.js
* creating assets/.babelrc
* creating assets/js/app.js
* creating assets/js/socket.js
* creating assets/package.json
* creating assets/css/app.css
* creating assets/static/favicon.ico
* creating assets/css/phoenix.css
* creating assets/static/images/phoenix.png
* creating assets/static/robots.txt

Fetch and install dependencies? [Yn] y
* running mix deps.get
* running cd assets && npm install && node node_modules/webpack/bin/webpack.js --mode development
* running mix deps.compile

We are almost there! The following steps are missing:

    $ cd docker-elixir

Then configure your database in config/dev.exs and run:

    $ mix ecto.create

Start your Phoenix app with:

    $ mix phx.server

You can also run your app inside IEx (Interactive Elixir) as:

    $ iex -S mix phx.server

config/dev.exsを修正

postgresの時と同様にhostnameをdbに設定します。

config/dev.exs
use Mix.Config

# Configure your database
config :dododo, Dododo.Repo,
  username: "root",
  password: "r00t",        #modify
  database: "dododo_dev",
  hostname: "db",          #modify
  show_sensitive_data_on_connection_error: true,
  pool_size: 10

#以下変更なし

docker imageをbuildする

$ docker build .

タグ付けしてからdockerhubにpush

$ docker images                                        #image idの確認
$ docker tag <image id> sanposhiho/phoenix_for_k8s
$ docker push sanposhiho/phoenix_for_k8s

docker-compose.ymlの修正

docker-compose.yml
version: "3"
services:    
  web:
    image: sanposhiho/phoenix_for_k8s 
    ports:   
      - '4000:4000'
    command: mix phx.server  
    depends_on:
      - db  

  db:                 #dbの設定を変更
    image: mysql:5.7
    ports:
      - "3306:3306"
    environment:
      MYSQL_ROOT_PASSWORD: r00t

dbの設定をmysql用に変更します。

Komposeを使って変換

$ kompose convert
INFO Kubernetes file "db-service.yaml" created
INFO Kubernetes file "web-service.yaml" created
INFO Kubernetes file "db-deployment.yaml" created
INFO Kubernetes file "web-deployment.yaml" created

色々作成されます。(便利)
webの部分は基本的に変更されていないのでdbの二つのファイルを見てみましょう

db-deployment.yaml

db-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.21.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: db
  name: db
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: db
  strategy: {}
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.21.0 ()
      creationTimestamp: null
      labels:
        io.kompose.service: db
    spec:
      containers:     #以下が変更されている
      - env:
        - name: MYSQL_ROOT_PASSWORD
          value: r00t
        image: mysql:5.7
        imagePullPolicy: ""
        name: db
        ports:
        - containerPort: 3306
        resources: {}
      restartPolicy: Always
      serviceAccountName: ""
      volumes: null
status: {}

postgresの時のdb-deployment.yamlとimageなどは勿論異なりますが、大きく変更はありません。

db-service.yaml

db-service.yaml
apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.21.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: db
  name: db
spec:
  ports:
  - name: "3306"
    port: 3306
    targetPort: 3306
  selector:
    io.kompose.service: db
status:
  loadBalancer: {}

こちらもpostgresの時と異なるのはportくらいですね

volumeの作成

postgresの時と同様にvolumeを作成します。
pvc-phoenix.yamlをpostgresの時と全く同じ内容で作成します。

pvc-phoenix.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pv-claim
spec:
  storageClassName: standard
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

db-deployment.yamlの方も変更しておきます。

db-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.21.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: db
  name: db
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: db
  strategy: {}
  template:
    metadata:
      annotations:
        kompose.cmd: kompose convert
        kompose.version: 1.21.0 ()
      creationTimestamp: null
      labels:
        io.kompose.service: db
    spec:
      containers:
      - env:
        - name: MYSQL_ROOT_PASSWORD
          value: r00t
        image: mysql:5.7
        imagePullPolicy: ""
        name: db
        ports:
        - containerPort: 3306
        volumeMounts:
          - mountPath: "/var/lib/mysql"
            name: mysqldata
        resources: {}
      restartPolicy: Always
      serviceAccountName: ""
      volumes:
        - name: mysqldata
          persistentVolumeClaim:
            claimName: pv-claim
status: {}

web-service.yamlの修正

外の世界からアクセスできるようにするためtype: NodePortに指定します。

web-service.yaml
apiVersion: v1
kind: Service
metadata:
  annotations:
    kompose.cmd: kompose convert
    kompose.version: 1.21.0 ()
  creationTimestamp: null
  labels:
    io.kompose.service: web
  name: web
spec:
  ports:
  - name: "4000"
    port: 4000
    targetPort: 4000
  selector:
    io.kompose.service: web
  type: NodePort              #追加
status:
  loadBalancer: {}

準備完了!

立ち上げてみましょう

$ kubectl apply -f db-deployment.yaml -f web-deployment.yaml -f pvc-phoenix.yaml -f web-service.yaml -f db-service.yaml
$ kubectl get pods
NAME                  READY   STATUS    RESTARTS   AGE
db-76fb87f99f-xlxm9   1/1     Running   0          9m41s
web-87795996-dgtkp    1/1     Running   0          3m49s
$ kubectl exec -it web-87795996-dgtkp mix ecto.create
The database for Dododo.Repo has been created
$ minikube service list
|----------------------|---------------------------|--------------|---------------------------|
|      NAMESPACE       |           NAME            | TARGET PORT  |            URL            |
|----------------------|---------------------------|--------------|---------------------------|
| default              | db                        | No node port |
| default              | kubernetes                | No node port |
| default              | web                       |              | http://192.168.64.2:32400 |
| kube-system          | kube-dns                  | No node port |
| kubernetes-dashboard | dashboard-metrics-scraper | No node port |
| kubernetes-dashboard | kubernetes-dashboard      | No node port |
|----------------------|---------------------------|--------------|---------------------------|

mix ecto.createも成功したのでDBもうまく作成されていることがわかります。

webのURLにアクセスして以下のページが表示されれば成功です。
スクリーンショット 2020-03-10 0.09.08.png

終わりに

記事にまとめる必要がないレベルで簡単でした。
メモ程度ですがどなたかの役に立てれば幸いです。

sanpo_shiho
京都で大学生してます。
https://sanposhiho.com/
fukuokaex
エンジニア/企業向けにElixirプロダクト開発・SI案件開発を支援する福岡のコミュニティ
https://fukuokaex.fun/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away