Skip to content

Instantly share code, notes, and snippets.

@jmini
Created December 28, 2021 11:53
Show Gist options
  • Save jmini/f96401f44b7f15c5964d92ce9dbdaf6f to your computer and use it in GitHub Desktop.
Save jmini/f96401f44b7f15c5964d92ce9dbdaf6f 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")));
}
}
@jmini
Copy link
Author

jmini commented Dec 28, 2021

Original blog post: How To Use the Official NGINX Docker Image

How to create the image:

jbang CreateWebserver.java

This is using the GoogleContainerTools/jib project to create the image.

docker images returns:

REPOSITORY                                                          TAG         IMAGE ID       CREATED        SIZE
webserver                                                           latest      5b649c0afba7   52 years ago   141MB

How to run the server (same command as in the original blog post):

docker run -it --rm -d -p 8080:80 --name web webserver

Visit http://localhost:8080/, you will see the html page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment