Let's say I have a static
variable counter
in my java application, that counts every hit on a website.
Something like below:
int static counter = 0;
Now this java application is running inside a docker container deployed on multiple hosts that is H1
and H2
.
Now, let say the application running inside the container of host H1
has counter value updated to say 1, now ideally this value 1 should also be reflected on an application that is running in a container deployed in a host H2
I am assuming this because same application is running on different hosts.
How docker achieve that ?
CodePudding user response:
Let's say I have a static variable...
You will get inconsistent behavior in a variety of environments. This even goes back to classic old-school when-XML-was-trendy Java application servers; even then it was known that a static variable could be incorrectly shared between instances of the application, or not shared when you expected it to be.
...deployed on multiple hosts...
Each host runs its own separate copy of the application. The static variable is not shared. If you ever restart the application or deploy it on a different host, the static variable's value is lost, and the next instance of the application will start over at zero.
None of this has anything to do with Docker. In some ways Docker makes the problem a little worse; if you're using a clustered container system like Kubernetes, it's very easy to have multiple copies of the application, it's very routine to delete and recreate them, and sometimes the cluster will delete the container under you.
The solution to this is the same, whether you're using containers or not: store any data that needs to be shared in a data store outside any particular instance of the process. Anything that needs a life span longer than an individual request probably needs to be persisted in some sort of database or persistent cache. If you're in the Spring ecosystem, the Spring Data subproject has support for a variety of data stores; even if not, looking at the systems it supports can give you an idea of the range of possible databases. For just a simple request counter, Redis is often a straightforward simple-to-deploy option.