To achieve real-time obstacle avoidance for underwater robots, the artificial potential field method can be selected as the obstacle avoidance path planning algorithm. However, this method applies a large attractive force to the underwater robot when it is far from the target point, causing it to collide with obstacles. Additionally, when the underwater robot just enters the repulsion influence zone, the repulsion force that it experiences undergoes an abrupt change, resulting in a non-smooth obstacle avoidance path. Furthermore, developing the obstacle avoidance function based on software platforms such as MATLAB has a long algorithm verification cycle, and it is difficult to transfer the algorithm model to practical scenarios. Therefore, this paper proposes an underwater robot obstacle avoidance method based on ROS. Firstly, a dynamic adjustment factor is introduced into the potential field function of the artificial potential field method to redefine the obstacle influence zone, and an improved artificial potential field method is designed as the obstacle avoidance path planning algorithm for underwater robots. The experiment is conducted on the ROS simulation platform, and the results show that the improved algorithm can solve the two problems existing in the artificial potential field method. Secondly, nodes required for underwater robot obstacle avoidance are established based on the ROS operating system, and the improved artificial potential field method is integrated into the obstacle avoidance path planning node. Finally, the obstacle avoidance experiment of the Bluerov2 underwater robot is conducted in a pool, and the experimental results demonstrate that the proposed method can achieve real-time obstacle avoidance for underwater robots.