diff --git a/react-java-mysql/README.md b/react-java-mysql/README.md index 174f586..b4de88e 100644 --- a/react-java-mysql/README.md +++ b/react-java-mysql/README.md @@ -1,5 +1,5 @@ ## Compose sample application -### React application with a NodeJS backend and a MySQL database +### React application with a Spring backend and a MySQL database Project structure: ``` diff --git a/react-java-mysql/backend/src/main/java/com/company/project/configuration/DockerSecretsProcessor.java b/react-java-mysql/backend/src/main/java/com/company/project/configuration/DockerSecretsProcessor.java new file mode 100644 index 0000000..a1858f2 --- /dev/null +++ b/react-java-mysql/backend/src/main/java/com/company/project/configuration/DockerSecretsProcessor.java @@ -0,0 +1,30 @@ +package com.company.project.configuration; + +import java.io.IOException; +import java.nio.charset.Charset; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.util.StreamUtils; + +/** + * Read property from docker secret file. + */ +public class DockerSecretsProcessor implements EnvironmentPostProcessor { + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { + Resource resource = new FileSystemResource("/run/secrets/db-password"); + if (resource.exists() && System.getProperty("MYSQL_PASSWORD") == null) { + try { + String dbPassword = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()); + System.setProperty("MYSQL_PASSWORD", dbPassword); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } +} diff --git a/react-java-mysql/backend/src/main/resources/META-INF/spring.factories b/react-java-mysql/backend/src/main/resources/META-INF/spring.factories new file mode 100644 index 0000000..e585c2f --- /dev/null +++ b/react-java-mysql/backend/src/main/resources/META-INF/spring.factories @@ -0,0 +1 @@ +org.springframework.boot.env.EnvironmentPostProcessor=com.company.project.configuration.DockerSecretsProcessor diff --git a/react-java-mysql/docker-compose.yaml b/react-java-mysql/docker-compose.yaml index b1998a4..50a892e 100644 --- a/react-java-mysql/docker-compose.yaml +++ b/react-java-mysql/docker-compose.yaml @@ -2,19 +2,28 @@ version: "3.7" services: backend: build: backend + restart: always + secrets: + - db-password environment: MYSQL_HOST: db networks: - react-spring - spring-mysql depends_on: - - db + db: + condition: service_healthy db: environment: MYSQL_DATABASE: example MYSQL_ROOT_PASSWORD_FILE: /run/secrets/db-password image: mysql:8.0.19 restart: always + healthcheck: + test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "--silent"] + interval: 3s + retries: 5 + start_period: 30s secrets: - db-password volumes: