<p>I have a rails project that using postgres database. I want to build a database server using Kubernetes and rails server will connect to this database.</p>

<p>For example here is my defined <code>postgres.yml</code></p>

<pre><code>apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  selector:
    app: postgres
  ports:
  - name: "5432"
    port: 5432
    targetPort: 5432
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: postgres
spec:
  replicas: 1
  strategy:
    type: Recreate
  template:
    metadata:
      labels:
        app: mysql
    spec:
      containers:
      - env:
        - name: POSTGRES_DB
          value: hades_dev
        - name: POSTGRES_PASSWORD
          value: "1234"
        name: postgres
        image: postgres:latest
        ports:
        - containerPort: 5432
        resources: {}
        stdin: true
        tty: true
        volumeMounts:
        - mountPath: /var/lib/postgresql/data/
          name: database-hades-volume
      restartPolicy: Always
      volumes:
      - name: database-hades-volume
        persistentVolumeClaim:
          claimName: database-hades-volume
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: database-hades-volume
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 100Mi
</code></pre>

<p>I run this by following commands: <code>kubectl run -f postgres.yml</code>.</p>

<p>But when I try to run rails server. I always meet following exception:</p>

<pre><code>PG::Error
invalid encoding name: utf8
</code></pre>

<p>I try to forwarding port, and rails server successfully connects to database server:</p>

<pre><code>$ kubectl get pods
NAME                        READY     STATUS    RESTARTS   AGE
postgres-3681891707-8ch4l   1/1       Running   0          1m
</code></pre>

<p>Then run following command:</p>

<pre><code>kubectl port-forward postgres-3681891707-8ch4l 5432:5432
</code></pre>

<p>I think this solution not good. How can I define in my <code>postgres.yml</code> so I don't need to port-forwarding manually as above.</p>

<p>Thanks</p>

<p>You can try by exposing your service on NodePort and then accessing the service on that port. </p>

<p>Check here  <a href="https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport" rel="nofollow noreferrer">https://kubernetes.io/docs/concepts/services-networking/service/#type-nodeport</a></p>
