Docker Setup
Finally we are going to setup and run our first container. Excited ?!
Alright, lets begin. Bring up the ubuntu terminal we setup in the previous article.
Setup DockerHub Account
DockerHub is a cloud-based registry service to store our images. Consider it as GitHub for images. Here are the steps
Let's complete the setup now
Now our setup is done.
Let's verify.
Run command sudo docker run hello-world. We'll get a very long trail of logs but this is specifically what we are looking for
...
Hello from Docker!
This message shows that your installation appears to be working correctly.
....
This confirms our setup is now done.
Let's run our own app in docker
To test we'll create our java app. Create a new java project. In pom.xml add the code below so we can have the jar
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
This will do things for us
Now, simply add a Main class to do "Hello World !" in main/java
public class Main {
public static void main(String[] args) {
System.out.println("Hello from java app");
}
}
Once done, we need to verify if it works fine. Bring up the windows terminal or mac, navigate to project's root i.e. where pom.xml resides and run mvn clean package this should give us a jar file in target folder
Run java -jar target/<jar name> that should log "Hello World !"
Writing our dockerfile
As discussed earlier, we need to tell docker what all are the dependency our app needs to run properly and what steps need to start it.
Let's go ahead and do that
# Bring in the OS and java setup
# This will bring up a tiny little container with ubuntu and java setup
FROM openjdk:21-jdk-slim
# This will setup location for our next command execution
WORKDIR /app
# Copy the jar with a different name in /app
COPY target/DockerJavaDemo-1.0-SNAPSHOT.jar app.jar
# run the jar
ENTRYPOINT ["java", "-jar", "app.jar"]
Now we need to create an image docker image. In the same terminal where we ran our maven command run wsl this will open the ubuntu terminal at the same location
Now build the image with docker build -t devdanish.in:dockerJavaDemo .
Wait, it might take sometime. Then check if the image is created with docker images | grep dockerJavaDemo
Now time to run our application
docker run devdanish.in:dockerJavaDemo
Hello from java app
Hello from java app
And that's it. We have now successfully ran our application in docker environment. Now this image can help us execute our application in environment without any external setup required.
In the next article, we'll run Springboot and node applications in docker and learn to pass environment variables.
Since I get time to draft these only on the weekends, you can checkout my notes at technotes.devdanish.in/docker