我正在尝试将 spring boot docker 容器连接到 mongodb docker 容器。在开发 Spring Boot 应用程序时,我使用了 MongoDB docker 容器,其端口 27017 通过 docker run -p 27017:27017 mongo:3.4 映射到主机的 27017 端口。开发完成后,我将 Spring 应用程序容器化,但容器化的 Spring 应用程序无法连接到 mongodb 容器。我知道问题是 spring 应用程序正在本地主机上寻找 mongodb。我的问题是我应该如何修改应用程序,以便它使用 mongodb 容器的地址,而不是在本地主机上查找 mongodb?
我的数据库连接是用下面的类处理的:
public class DB {
private final Datastore datastore;
private Morphia morphia;
/**
* Constructor for creating database instance
*/
public DB() {
morphia = new Morphia();
morphia.mapPackage("users");
datastore =
morphia.createDatastore(new MongoClient(), "test");
datastore.ensureIndexes();
}
/**
* Inserts given user to the database
*
* @param u a newly created user.
*/
public void addUser(User u) {
datastore.save(u);
}
/**
* Fetches and prints all documents in database
*
* @return json array of all documents in database
*/
public String getUsers() {
final Query<User> query = datastore.createQuery(User.class);
final List<User> employees = query.asList();
return objToJson(employees);
}
/**
* Returns the user with the specified ID.
*
* @param userID is the ID of the document in database
* @return document in json format
*/
public String getUser(ObjectId userID) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
final List<User> employees = query.asList();
return objToJson(employees);
}
/**
* Deletes the document with the given ID from database.
*
* @param userID is the ID of the document to be removed
*/
public void removeUser(ObjectId userID) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
datastore.delete(query);
}
/**
* Deletes all documents from database.
*/
public void removeUsers() {
final Query<User> query = datastore.createQuery(User.class);
datastore.delete(query);
}
/**
* Updates the fields of the document with given ID.
*
* @param userID is the ID of the document to be updated
* @param newUser contains the new fields
* @return results of the update in json format
*/
public String updateUser(ObjectId userID, User newUser) {
final Query<User> query = datastore.createQuery(User.class)
.field("id").equal(userID);
final UpdateOperations<User> updateOperations = datastore.createUpdateOperations(User.class);
if (newUser.getFirst_name() != null) {
String newName = newUser.getFirst_name();
updateOperations.set("first_name", newName);
}
if (newUser.getLast_name() != null) {
String newLastName = newUser.getLast_name();
updateOperations.set("last_name", newLastName);
}
if (newUser.getSalary() != 0) {
int newSalary = newUser.getSalary();
updateOperations.set("salary", newSalary);
}
final UpdateResults results = datastore.update(query, updateOperations);
return results.toString();
}
/**
* Translate object lists to the json array.
*
* @param query is the list of the user objects
* @return json array of the given users
*/
private String objToJson(List<User> query) {
List<String> attsToRemove = Arrays.asList(new String[]{"className"});
List<DBObject> dbObjList = new ArrayList<>(query.size());
DBObject dbObj;
for (Object obj : query) {
dbObj = morphia.toDBObject(obj);
for (int i = 0; i < attsToRemove.size(); i++) {
dbObj.removeField(attsToRemove.get(i));
}
dbObjList.add(dbObj);
}
String json = JSON.serialize(dbObjList);
return json;
}
这是我的 Spring Boot Controller
@RestController
public class DemoController {
DB mongodb = new DB();
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index() {
return "Greetings from Spring Boot";
}
@RequestMapping(value = "/users/{user_id}", method = RequestMethod.GET)
public String getUser(@PathVariable("user_id") ObjectId userID) {
return mongodb.getUser(userID);
}
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String getUsers() {
return mongodb.getUsers();
}
@RequestMapping(value = "/users", method = RequestMethod.POST)
public void createUser(@RequestBody User u) {
try {
mongodb.addUser(u);
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users", method = RequestMethod.DELETE)
public void deleteUsers() {
try {
mongodb.removeUsers();
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users/{user-id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable("user-id") ObjectId userID) {
try {
mongodb.removeUser(userID);
} catch (Exception e) {
System.out.println(e.toString());
}
}
@RequestMapping(value = "/users/{user-id}", method = RequestMethod.PUT)
public String updateUser(@PathVariable("user-id") ObjectId userID, @RequestBody User u) {
return mongodb.updateUser(userID, u);
}
这是我的 Dockerfile:
来自 frolvlad/alpine-oraclejdk8:slim
体积/tmp
添加 demo-0.0.1-SNAPSHOT.jar app.jar
暴露27017
曝光8080
运行 sh -c 'touch/app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [“sh”,“-c”,“java $JAVA_OPTS -Djava.security.egd=文件:/dev/./urandom -jar/app.jar”]
我阅读了提到的解决方案 here 和 here 。还阅读了几个教程,但我无法将这些解决方案中的任何一个适合我的代码。在我的代码中,我应该更改哪里?
最佳答案
主要问题是您的容器不在同一网络中。我想你可以通过这个 How to run Spring Boot and MongoDB in Docker containe 找到一个工作示例。这是一个简短的摘录:
docker network create spring_demo_net
创建网络docker run --name spring-demo-mongo --network=spring_demo_net -v/home/ubuntu/mongo-data:/data/db -d mongo
启动 mongo 容器- 在应用程序属性中修改 mongo 主机,如下
spring.data.mongodb.uri=mongodb://spring-demo-mongo/YOUR_DB
此处 spring-demo-mongo是您在步骤 1 中创建的容器的名称。
由于您没有使用 SpringData 存储库,因此它无法工作,因此您需要通过显式传递主机和端口来创建 MongoClient:
MongoClient mongoClient2 = new MongoClient("spring-demo-mongo", 27017);
docker build --tag=spring-demo-1.0
使用标签构建 docker 镜像docker run -d --name spring-demo --network=spring_demo_net -p 8080:8080 spring-demo-1.0
启动你的docker镜像
关于java - 将 Spring Boot Docker 容器连接到 MongoDB docker 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44439587/