You can only use 'localhost' if the code is running in the same machine with the database. Otherwise, you have to use exact host name.
From the exception, it looks like that you are trying to...