Build mysql or postgresql use S2I - unix1998/technical_notes GitHub Wiki

build MySQL or PostgreSQL image using Source-to-Image (S2I) instead of using pre-built images from Docker Hub. OpenShift's S2I allows you to create container images directly from your source code, which can include custom configurations and scripts necessary for your database setup.

Building a MySQL or PostgreSQL Image Using S2I

Here's a step-by-step guide to building a custom MySQL or PostgreSQL image using S2I in OpenShift:

  1. Prepare Your Source Code and Configuration:

    • Create a repository that contains all necessary configurations, initialization scripts, and Dockerfiles for your database.
  2. Create an S2I Builder Image:

    • You need to create an S2I builder image that includes the base OS, necessary database binaries, and S2I scripts.
  3. S2I Scripts:

    • assemble: This script will install your database, configure it, and set up any initial data or schemas.
    • run: This script will start the database server.
    • save-artifacts: (optional) This script can be used to save built artifacts between builds.

Example: Creating a Custom MySQL Image

1. Create a Directory Structure

mkdir s2i-mysql
cd s2i-mysql
mkdir -p .s2i/bin

2. Create S2I Scripts

.s2i/bin/assemble:

#!/bin/bash
set -e

# Install MySQL (example using yum, adjust based on your base image)
yum install -y mysql-server

# Copy configuration files and initialization scripts
cp /tmp/src/my.cnf /etc/my.cnf
cp /tmp/src/init.sql /docker-entrypoint-initdb.d/

# Clean up
yum clean all

.s2i/bin/run:

#!/bin/bash
exec mysqld_safe

Make these scripts executable:

chmod +x .s2i/bin/assemble
chmod +x .s2i/bin/run

3. Create a Dockerfile

Dockerfile:

FROM centos:7

# Copy S2I scripts
COPY .s2i/bin/ /usr/libexec/s2i/

# Install dependencies (example for MySQL)
RUN yum install -y epel-release && \
    yum install -y mysql-server && \
    yum clean all

# Set labels used by OpenShift to describe the builder image
LABEL io.openshift.s2i.scripts-url=image:///usr/libexec/s2i

# Set default CMD
CMD ["run"]

4. Build the S2I Builder Image

docker build -t custom-mysql-s2i .

5. Create a New Build Configuration in OpenShift

oc new-build --name=my-custom-mysql --binary=true --strategy=docker

6. Start the Build

oc start-build my-custom-mysql --from-dir=. --follow

Deploying Your Custom Image

Once the custom image is built, you can deploy it like any other image in OpenShift:

oc new-app my-custom-mysql

Conclusion

By following the steps above, you can build your own MySQL or PostgreSQL image using S2I in OpenShift, tailored to your specific requirements. This approach gives you more control over the configuration and setup of your database compared to using pre-built images from Docker Hub.