DEV Community

Cover image for Wait for MongoDB, Postgres or MySql to start on Docker
Hugo Dias
Hugo Dias

Posted on • Updated on

Wait for MongoDB, Postgres or MySql to start on Docker

Originally posted in my blog

Quick tip here.

I was struggling to get this thing working so I need to share with you guys.

Assuming that you have an app depending on a MongoDB container:

version: "3.3"
services:
  web:
    build: .
    volumes:
      - "./app:/src/app"
    ports:
      - "3030:3000"
    links:
      - mongo
    depends_on:
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
volumes:
  mongo_data:
Enter fullscreen mode Exit fullscreen mode

In my case it's a NodeJS app.

The MongoDB is quite slow to get up, so when the app starts, the linked container is ready but not the database itself.

To solve this problem you can use a script to explicitly wait for MongoDB service to be up.

Add this to your Dockerfile

FROM node:latest

RUN mkdir /src


WORKDIR /src
ADD app/package.json /src/package.json
RUN npm install

EXPOSE 3000

## THE LIFE SAVER
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait /wait
RUN chmod +x /wait

## Launch the wait tool and then your application
CMD /wait && npm start
Enter fullscreen mode Exit fullscreen mode

And now change your docker-compose.yml file and adds a WAIT_HOSTS section

version: "3.3"
services:
  web:
    build: .
    volumes:
      - "./app:/src/app"
    ports:
      - "3030:3000"
    links:
      - mongo
    depends_on:
      - mongo
    environment:
      WAIT_HOSTS: mongo:27017
  mongo:
    container_name: mongo
    image: mongo
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
volumes:
  mongo_data:
Enter fullscreen mode Exit fullscreen mode

And that's it.

You can use it for any other service such as Postgres, MySQL, etc ...

To do this you just need to use commas:

version: "3"

services:

  mongo:
    image: mongo:3.4
    hostname: mongo
    ports:
      - "27017:27017"

  postgres:
    image: "postgres:9.4"
    hostname: postgres
    ports:
      - "5432:5432"

  mysql:
    image: "mysql:5.7"
    hostname: mysql
    ports:
      - "3306:3306"

  mySuperApp:
    image: "mySuperApp:latest"
    hostname: mySuperApp
    environment:
      WAIT_HOSTS: postgres:5432, mysql:3306, mongo:27017
Enter fullscreen mode Exit fullscreen mode

Hope it helps

Top comments (32)

Collapse
 
seankilleen profile image
Sean Killeen

Hey! I've noticed that in this post you use "guys" as a reference to the entire community, which is not made up of only guys but a variety of community members.

I'm running an experiment and hope you'll participate. Would you consider changing "guys" to a more inclusive term? If you're open to that, please let me know when you've changed it and I'll delete this comment.

For more information and some alternate suggestions, see dev.to/seankilleen/a-quick-experim....

Thanks for considering!

Collapse
 
warthog618 profile image
Kent Gibson

I for one hope that Hugo leaves his post as is - nice job Hugo - I've found it helpful.

The term "guys" in the context it is used refers to "persons of either sex" (ref Collins English Dictionary). That is the common usage.
You chose to take offence by insisting that the term is exclusive when there is no indication that any such thing was intended. The offence here is requesting that Hugo reword his post to suit your incorrect interpretation of the language. Stop it.

Thanks for considering!

Collapse
 
seankilleen profile image
Sean Killeen

For the record, I didn't take offense.

The defense of the dictionary term doesn't speak to what I'm speaking to, which is a feeling of inclusion. I am not suggesting that Hugo change anything except a small phrase, and I don't believe it would impact the helpfulness of the post at all.

As I explain in the linked post, it seemed like a minor change that could be made easily that my anecdotal evidence suggests would make others feel slightly more welcome, so seemed like a win to me. If you or he disagree, we'll have to leave it there.

Thread Thread
 
warthog618 profile image
Kent Gibson

I disagree, but unlike you I'm open to continuing the discussion.

The point of the dictionary defense is that the language is being used appropriately. You have no grounds for your request.

If there are anecdotal others that find "guys" in this context exclusive then the problem lies with them - they take offence when none if offered. You should be focusing your attention on educating them, rather than trying to rework the use of language to fit within your arbitrary definition of what they may consider to be inclusive.

Thread Thread
 
seankilleen profile image
Sean Killeen

I mostly didn't want to force someone to have a debate on the topic, given that I was dropping in to your post to make an ask of you.

My point is that while the dictionary definition means one thing, the perception of such wording in a specific context -- for example, the male-heavy tech industry -- is different than the dictionary definition. So while you're technically correct, your point is not the point I'm trying to converse around.

Yes, the dictionary definition is technically correct, and we can use that reason if we want. My experiment is that, based on my own anecdotal evidence from doing so, we can make the experience that much more welcoming for others with almost zero effort.

Thread Thread
 
warthog618 profile image
Kent Gibson

Firstly, not my post, so you aren't making an ask of me - I just happened to be reading it about the time you added your experiment, and I'm tired of this social justice go out of your way try to make everyone feel warm and fuzzy rubbish.

Secondly, you are concerned enough that you don't want to force a debate, yet you are happy to shut it down unilaterally? That is inconsistent. More likely you don't want to hear a different opinion.

My point is that your approach is wrong headed. You are trying to change the wrong thing, the author and their post, when the actual problem lies in the reader. Your approach is the easy one, as you can easily identify and make a request of the author, but that is not an excuse for trying to fix your anecdotal problem the wrong way.

Might there be readers who find "all" more inclusive than "guys"? Sure. Should we be changing our interpretation and usage of the language to suit THEIR interpretation? No - that is a slippery Orwellian slope.

Thread Thread
 
seankilleen profile image
Sean Killeen

I'm tired of this social justice go out of your way try to make everyone feel warm and fuzzy rubbish

The last heading of the post specifically addresses this:

"Roar! You're being politically correct / censoring / controlling! Social Justice! Blargh!"

This post is meant for those who are generally empathetic and want to improve the experiences people have within the community.

If you feel similar to the heading above after reading, you are not the target audience for this post, as you may be more interested in your own experiences than the feelings of others. Feel free to disregard this, but I hope you'll consider it someday.

My attitude is that it costs nothing to be kind. So my goal of the post, as stated in the post, was to make an observation and a suggestion -- which folks could choose to take or leave. The goal is not to turn someone's post into a battleground; should the author choose to react warmly to the observation (as many have), they could change the text at almost no cost. But I have no intention of arguing the value of empathy with someone else.

My post was intended to say "I did a thing -- others reacted warmly and felt more included. Might I therefore encourage that behavior more widely, so that even more others will feel more included or more warmly welcomed?" My anecdote wasn't a problem, you see -- it was an anecdotal solution, that I found by accident, and thought might be nicer to spread more widely.

Doesn't seem like the kind of thing that really needs much debate. I can't convince you to truly care about the perceptions other people might have over a dictionary definition (though I'd ask you to consider -- who gets to make definitions for things? Is it the marginalized?). And I believe my post was far from attempting some mandate of language; it was a (pretty positively worded) suggestion, and not at all a crusade. So the defensiveness is a little surprising.

My observation was pretty straight-forward: "Guys" doesn't mean all people (particularly in the perceptions of the underrepresented folks in our community). My ask wasn't egregious: would someone consider changing the language? And I'm not here to fight about it; someone can simply say "no" -- and some have -- and I've happily left it at that. It may be worth considering why this ask and approach feels like such an affront.

Thread Thread
 
warthog618 profile image
Kent Gibson

I'm glad you are aware that "It may be worth considering why this ask and approach feels like such an affront." I hope you get there soon.

You are correct in implying I am unconcerned about the perceptions of others - that is their business, not mine and not yours.

Your "pretty straight forward observation" is wrong.
Common usage is that "guys" in this context is gender neutral.
Sorry that you refuse to see that.

Your approach and ask is an affront because it tackles the problem from the wrong end - putting the onus of implementing the solution on the author who has done nothing untoward.

Further, your solution is misguided, as however you change the wording there will always be some, marginalised or not, that perceive it differently from what was intended. You will be endlessly reworking the language to remove the next perceived slight. Accept that the problem here is in the interpretation and move on.

Thread Thread
 
seankilleen profile image
Sean Killeen

So like I said previously, there's no real point in continuing this conversation -- you were never the intended target audience, as you would rather argue against changing to maybe help other people feel welcome. That's fine then; I'm not going to change your mind and I have no intention of making some grand argument here except "maybe this would help other people feel good with no effort, and maybe that's not such a hard/bad thing."

If you'd like to make arguments about why we should never change things because there will always be people that perceive it differently, you're simply not the intended recipient of my message. I don't know how to explain to you that you should care about other people, and what they might feel, despite what the dictionary definition of a word may mean. And I feel like the fact that you created your account today, and seemingly only to join in this discussion, further solidifies that.

So I wish you the best, and will likely be spending no more of my time on this conversation.

Thread Thread
 
warthog618 profile image
Kent Gibson

Yes I created this account explicitly to reply, as it was the first time I've been to this site (Google is my friend) and it was a necessary step to replying.
How does that invalidate or give less weight to my argument?
You are implying I'm only here to troll you?
I am here because I found your request to be offensive.
To reply to a thread that is months old requesting a one word change to maybe make some people feel better about themselves is both absurd and disrespectful to the author.

It is telling that you are unwilling to converse with those outside your target audience. But as long as you feel good about yourself. Have a good one.

Thread Thread
 
seankilleen profile image
Sean Killeen

I look forward to seeing your other contributions to the community here, and wish you all the best in the future.

Thread Thread
 
warthog618 profile image
Kent Gibson

You do realise how easy it is to interpret that first clause as sarcasm, implying that my opinions are worth less than yours as I'm new here?
I'm trying to give you the benefit of the doubt, but my overwhelming suspicion is that, consciously or subconsciously, that was the intent.

Do you see the problem with trying to tweak wording yet?
In the process of trying to fix one word your own words can be interpreted as inherently biased and unwelcoming.
So consider adding hypocrisy to the list of problems with your approach.

And have a good one. (and yes - that can potentially be misinterpreted as well - but I'll leave that up to you ;-)

Thread Thread
 
stenpittet profile image
Sten

Hi @Kent, @Sean, I just want to help find a middle ground here. Dev.to is a great community and it's a bit disconcerting to find such discussion here. Especially considering that most of it is not really about the article itself (thanks Hugo for writing it).

I think we can all agree that being inclusive is better than the opposite, and I think that Sean meant well by reaching out. I believe that a direct outreach via DM or email would have been better, and I encourage that type of approach in the future as it gives the author an opportunity to respond in a private space.

However, I would not describe the request as offensive in itself. @Kent, it's great that you joined the community, but please take some time to get familiar with it. The code of conduct itself promotes "using welcoming and inclusive language", which is what we're talking about here.

It would be great if we do not push this debate further. @Kent I think you made a good point about how to approach authors, but @Sean's initiative is quite in line with what the community is pushing for.

Let's not forget to thank Hugo for his work.

Thread Thread
 
peter profile image
Peter Kim Frank

Thanks @stenpittet , well put on all counts. Our Code of Conduct clearly outlines our position that all community members should make an effort to use welcoming and inclusive language. I don't think the usage of "guys" presents a violation whatsoever (I've surely used such language without second thought many times), but I absolutely agree that Sean's (@seankilleen ) heart is in the right place with his experiment. I, for one, think it's a great nudge for all of us, and the outcome is hopefully that we're all a bit more mindful about the language we use and how it affects others.

Kent (@warthog618 ), welcome to the community, and thank you for joining the conversation. I'm encouraged that you and Sean each had an outlet to express your points without it devolving into ad-hominems and the like. We're all too familiar with the pedantic, zero-sum, spirals that can oftentimes affect other online communities, and we're hoping to avoid that here. Thank you both for remaining civil and respectful.

I recognize that all of us are trying to make a legitimate attempt to further a discussion that's important to us, but it looks like this specific back-and-forth has run its course. I'll echo Sten's hope that we can leave this for now.

Hugo (@hugodias ), thanks for a great article!

Collapse
 
anselmobattisti profile image
Anselmo Battisti

Hey guy! go find some work to do and stop to be so annoying about the word "guy"!

Collapse
 
seankilleen profile image
Sean Killeen

Totally cool and productive response to a comment from almost a year ago. 👍

Collapse
 
millochono profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
Sho Fukamachi

Why? Please keep SJW bullshit out of development. We are a community focused on building things, not stroking the egos of immature adults who take offense to using certain words.

Collapse
 
seankilleen profile image
Sean Killeen

If you take a step back, does this not seem perhaps a small bit out of line with the original point I raised, which is 1) months old 2) pretty polite 3) totally open to disagreement and 4) not offended in any sense of the word? If you consider attempting to make folks feel welcome to be "SJW bullshit", I only hope I don't have to cross paths with you on a team. I feel pretty bad that Hugo's great post has been derailed by this discussion (which was an easy & civil discussion on many posts), so we'll have to agree to disagree on this.

Since it appears you joined today specifically to leave this comment, I can only say: welcome to the DEV community! I look forward to seeing your contributions.

Collapse
 
dm17 profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
dm17

Very disturbing post, @seankilleen . Why do you work free of charge for the globalist's language control agenda. Now please be respectful, my pronouns are mein, fuhrer.

Collapse
 
seankilleen profile image
Sean Killeen

this...doesn't seem like a productive way to engage with a months-old conversation that was pretty respectful and allowed for disagreement. Maybe troll on other communities. Not taking the bait. 👍

Collapse
 
anselmobattisti profile image
Anselmo Battisti

Now there is another way to do it!

You can use healthcheck!

services:
app:
build: .
command: npm start
ports:
- "8080:8080"
volumes:
- .:/usr/app
networks:
- express-mongo-network
healthcheck:
test: ["CMD", "curl", "-f", "mongo:27017"]
interval: 30s
timeout: 10s
retries: 5

Collapse
 
kferrone profile image
Kelly Ferrone

Hey thanks its a nice one. I just want to tweak a bit your Dockerfile to make the image smaller and cleaner. Check this out:

FROM node:latest

RUN mkdir /src

WORKDIR /src
ADD app/package.json /src/package.json

## THE LIFE SAVER
RUN npm install && \
    curl -L https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait \
    -o ./node_modules/.bin/wait && \
    chmod +x ./node_modules/.bin/wait

EXPOSE 3000

ENTRYPOINT [ "npm" ]

## Launch the wait tool and then your application
CMD [ "run", "start:docker" ]

in your package.json scripts make a script like so

"start:docker": "wait && npm start"

Any executable in the node_modules/.bin folder is automatically added to your path when running thorugh npm. Enjoy!

Collapse
 
dmfay profile image
Dian Fay

Very nice! I've used wait-for-it.sh but the environment variable parsing makes this that little bit more convenient.

Collapse
 
wkrea profile image
wkrea

Hi.

Please let me know, are you using Docker for Windows? Or Linux?

Thanks a lot

Collapse
 
dmfay profile image
Dian Fay

Linux; I haven't used Windows for several years. If your Mongo container is constantly restarting like you mentioned below, that sounds like a problem internal to it. Try starting it outside the docker-compose environment so you can diagnose the problem without all the other stuff getting in the way. Good luck!

Collapse
 
greening profile image
Dan Greening

Just a note for others: There are security risks in using the application as described, because the author (or someone who breaks into the author's account) could change the application to do other things, like crash or worse. So use the application as described for tests, but not production. Or clone the repository, examine and build it yourself (what I plan to do).

As a developer, I've watched other developers take security lightly, and this can lead to dramatic news articles about millions of user accounts being broken into, SO, don't be the developer that caused that.

Collapse
 
inspiraller profile image
steve

So how does this work if you want to include other variables in environment?

eg

    environment:
      - WAIT_HOSTS: mongo:27017 
      - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
      - ME_CONFIG_BASICAUTH_USERNAME=${MONGO_USER}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sarasagunawardhana profile image
Sarasa Gunawardhana

Thank you brother.. Very helpful

Collapse
 
naveensadhana profile image
NaveenSadhana • Edited

Hi Mr. Dias,

Can you explain how do we write CMD command for java application and wait function

Collapse
 
selahattinunlu profile image
Selahattin Ünlü • Edited

It's really "life saver" as you mentioned it. Thanks for sharing, you've saved my day!

Collapse
 
svenvarkel profile image
Sven Varkel

Thanks for good writeup and tip on "wait". This helped me solve startup sequence problems with my docker stack (a node.js API, mongob, rabbitmq and redis) where rabbitmq is quite lazy to start.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.