Skip to content

Instantly share code, notes, and snippets.

@maxandersen
Forked from jmini/CreateWebserver.java
Created December 29, 2021 05:37
Show Gist options
  • Save maxandersen/a737b3f192e798a6315fed091a7a701c to your computer and use it in GitHub Desktop.
Save maxandersen/a737b3f192e798a6315fed091a7a701c to your computer and use it in GitHub Desktop.
Create a docker image with Jib
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS com.google.cloud.tools:jib-core:0.20.0
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import com.google.cloud.tools.jib.api.Containerizer;
import com.google.cloud.tools.jib.api.DockerDaemonImage;
import com.google.cloud.tools.jib.api.Jib;
import com.google.cloud.tools.jib.api.buildplan.AbsoluteUnixPath;
// inspired by https://www.docker.com/blog/how-to-use-the-official-nginx-docker-image/
// create the image with jbang: "jbang CreateWebserver.java"
// run the image with "docker run -it --rm -d -p 8080:80 --name web webserver"
public class CreateWebserver {
public static void main(String... args) throws Exception {
Path root = Files.createTempDirectory("tmp");
Path htmlFolder = root.resolve("html");
Files.createDirectories(htmlFolder);
Path indexFile = htmlFolder.resolve("index.html");
String content = ""
+ "<!doctype html>\n"
+ "<html lang=\"en\">\n"
+ "<head>\n"
+ " <meta charset=\"utf-8\">\n"
+ " <title>Docker Nginx</title>\n"
+ "</head>\n"
+ "<body>\n"
+ " <h2>Hello from Nginx container</h2>\n"
+ " <p>Created with jib</p>\n"
+ "</body>\n"
+ "</html>";
Files.write(indexFile, content.getBytes(StandardCharsets.UTF_8));
Jib.from("nginx:latest")
.addLayer(Arrays.asList(htmlFolder), AbsoluteUnixPath.get("/usr/share/nginx/"))
.containerize(Containerizer.to(DockerDaemonImage.named("webserver")));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment